Django - 使用模板中的变量调用列表或dict项

时间:2018-04-17 10:40:00

标签: python django list templates dictionary

我正在尝试使用该模板中的变量调用模板中的字典或列表对象而没有结果。

我正在尝试的是与这个通用的python代码相同:

keylist=[
        'firstkey',
        'secondkey',
        'thirdkey',
        ]
exampledict={'firstkey':'firstval',
             'secondkey':'secondval',
             'thirdkey':'thirdval',
             }

for key in keylist:
    print(exampledict[key])

#Produces:
    #firstval
    #secondval
    #thirdval

django模板中的工作方式略有不同。 我有一个变量定义为key ='firstkey'传递给模板。 如果我想打电话给同一个字典:

{{ exampledict.firstkey }} #Produces: firstval
{{ exampledict.key }} #Produces: None

Django模板for循环还有一个生成的变量forloop.counter0,从第一个循环中的0增加到最后一个循环中的n-1,这不能调用列表对象。 我有一个清单:

tabletitles=['first table', 'second table', 'third table']

我想在一个循环中调用和创建表,将上面各个表的表标题放在上面:

{% for table in tables %}
<h3> first table </h3>
<table>
...
</table>
{% endfor %}

在这种情况下我想做的是

{% for table in tables %}
<h3> {{ tabletitles.forloop.counter0 }} </h3>
<table>
...
</table>
{% endfor %}

这也不起作用,因为我不能使用单独的变量来调用模板中的dict或列表的对象。 有没有办法让这个工作,或更好的方式一起完成这一切?

1 个答案:

答案 0 :(得分:3)

Django模板语言不允许您使用变量访问字典键和列表。您可以编写模板标记来执行此操作(例如,请参阅this question),但在您的情况下,这是一个更简单的替代方案。

在您看来,将表格和标题压缩在一起

tables_and_titles = zip(tables, tabletiles)

然后在模板中循环浏览它们。

{% for table, title in tables_and_titles %}
    {{ title }}
    <table>
    {{ table }}
    </table>
{% endfor %}
相关问题