【发布时间】:2018-09-27 07:00:20
【问题描述】:
我正在尝试使用模板中的变量调用模板中的字典或列表对象,但没有结果。
我正在尝试的内容与此通用 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 loops 还有一个生成变量 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 %}
这也不起作用,因为我不能使用单独的变量来为模板中的字典或列表调用对象。 有没有办法让它工作,或者有更好的方法一起做?
【问题讨论】:
标签: python django list templates dictionary