0

I need to access data in the nested list fdata but I get nothing when using the template variables i & j to access them. I can access the values using something like {{ fdata.1.0 }} however.

Here's the context data

fdata = [[0, 0, 0], [4, 1, 2], [1, 0, 0], [0, 0, 0], [0, 0, 0]]

flabels = ['image', 'video', 'document']

users = [<User: admin>, <User: test>, <User: neouser>, <User: hmmm>, <User: justalittle>]

And this is the code in the template.

{% for file_type in flabels  %}
    {
        {% with i=forloop.counter0 %} 
        label: {{file_type}},
        data: [            
            {% for user in users %}
                {% with j=forloop.counter0 %}
                    {{ fdata.j.i }},                                  
                {% endwith %}
            {% endfor %}                
        ],
        {% endwith %}
    }
{% endfor %}
2
  • 1
    why not use a dictionary instead? Commented Jul 17, 2018 at 18:28
  • You can't use a template variable for that, only hard coded numbers can be used there. But your question is answered here: stackoverflow.com/questions/8948430/… Commented Jul 17, 2018 at 19:24

1 Answer 1

1

Im pretty sure you cant do that fdata.j.i

You can use templatetags...

Create one folder called templatetags and one file inside it (i'll call it table_templatetags.py) Obs.: Make sure to create empty file called __init__.py so django can understand that can read that folder

app/templatetags/table_templatetags.py

from django import template

register = template.Library()

@register.simple_tag(name='get_pos')
def get_position(item, j, i): 
    return item[j][i]

In your HTML

<!-- Place this load in top of your html (after the extends if you using) -->    
{% load table_templatetags %} 

<!-- The rest of your HTML -->

{% for file_type in flabels  %}
    {
        {% with i=forloop.counter0 %} 
        label: {{file_type}},
        data: [            
            {% for user in users %}
                {% with j=forloop.counter0 %}
                    {% get_pos fdata j i %}, <!-- Call your brand new templatetag -->
                {% endwith %}
            {% endfor %}                
        ],
        {% endwith %}
    }

Some snippet mine: https://github.com/Diegow3b/django-utils-snippet/blob/master/template_tag.MD

Django Docs: https://docs.djangoproject.com/pt-br/2.0/howto/custom-template-tags/

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks but arguments can't be passed to the filter in that format, I've tried {{ fdata|get_position:j,i }} but that only passes one argument
sry i forgot to place the decorator

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.