Python Django-使用模板中的变量调用列表或dict项
我试图使用模板中的变量调用模板中的dictionary或list对象,但没有结果 我尝试的内容与下面的一般python代码相同:Python Django-使用模板中的变量调用列表或dict项,python,django,list,templates,dictionary,Python,Django,List,Templates,Dictionary,我试图使用模板中的变量调用模板中的dictionary或list对象,但没有结果 我尝试的内容与下面的一般python代码相同: keylist=[ 'firstkey', 'secondkey', 'thirdkey', ] exampledict={'firstkey':'firstval', 'secondkey':'secondval', 'thirdkey':'third
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 template 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 %}
{tables%]中的表的%
第一桌
...
{%endfor%}
在这种情况下,我想做的是
{% for table in tables %}
<h3> {{ tabletitles.forloop.counter0 }} </h3>
<table>
...
</table>
{% endfor %}
{tables%]中的表的%
{{tabletitles.forloop.counter0}
...
{%endfor%}
这也不起作用,因为我不能使用单独的变量为模板中的dict或list调用对象。
有没有一种方法可以实现这一点,或者有更好的方法可以一起实现这一点?Django模板语言不允许您访问带有变量的字典键和列表。您可以编写一个模板标记来实现这一点(参见示例),但在您的例子中,有一个更简单的替代方法 在您的视图中,将表格和标题压缩在一起
tables_and_titles = zip(tables, tabletiles)
然后在模板中循环浏览它们
{% for table, title in tables_and_titles %}
{{ title }}
<table>
{{ table }}
</table>
{% endfor %}
{%用于表格,表格中的标题和标题%}
{{title}}
{{table}}
{%endfor%}
Django模板语言不允许您使用变量访问字典键和列表。您可以编写一个模板标记来实现这一点(参见示例),但在您的例子中,有一个更简单的替代方法
在您的视图中,将表格和标题压缩在一起
tables_and_titles = zip(tables, tabletiles)
然后在模板中循环浏览它们
{% for table, title in tables_and_titles %}
{{ title }}
<table>
{{ table }}
</table>
{% endfor %}
{%用于表格,表格中的标题和标题%}
{{title}}
{{table}}
{%endfor%}
我花了一段时间才重新开始,完全解决了问题,完全按照描述执行,谢谢!我花了一段时间才回复,完全解决了问题,完全按照描述执行,谢谢!