在Djang中使用模板变量访问嵌套列表数据

2024-09-30 20:29:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要访问嵌套列表fdata中的数据,但是当使用模板变量i&;j访问它们时,我什么也得不到。但是,我可以使用{{ fdata.1.0 }}之类的方法访问这些值。你知道吗

这是上下文数据

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>]

这是模板中的代码。你知道吗

{% 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 %}

Tags: 数据in模板fortypewithusersfile
1条回答
网友
1楼 · 发布于 2024-09-30 20:29:44

我很确定你不能那样做fdata.j.i

你可以使用模板标签。。。你知道吗

创建一个名为templatetags的文件夹,并在其中创建一个文件(我称之为table_templatetags.pyObs。注意:确保创建名为{u init}.py的空文件,以便django能够理解可以读取该文件夹的文件

应用程序/模板标签/表格_模板标签.py

from django import template

register = template.Library()

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

在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 %}
    }

我的一些片段:https://github.com/Diegow3b/django-utils-snippet/blob/master/template_tag.MD

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

相关问题 更多 >