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 %}
MNSH
  • 975
  • 9
  • 13
  • 1
    why not use a dictionary instead? – Ashish Acharya Jul 17 '18 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: https://stackoverflow.com/questions/8948430/get-list-item-dynamically-in-django-templates – little_birdie Jul 17 '18 at 19:24

1 Answers1

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/

MNSH
  • 975
  • 9
  • 13
Diego Vinícius
  • 2,125
  • 1
  • 12
  • 23