【问题标题】:Django - Calling list or dict item using a variable in templateDjango - 使用模板中的变量调用列表或字典项目
【发布时间】: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


    【解决方案1】:

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

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

    tables_and_titles = zip(tables, tabletiles)
    

    然后在您的模板中一起循环遍历它们。

    {% for table, title in tables_and_titles %}
        {{ title }}
        <table>
        {{ table }}
        </table>
    {% endfor %}
    

    【讨论】:

    • 花了我一段时间才回过神来,绝对解决了完全按照描述实现的问题,谢谢!
    猜你喜欢
    • 2011-03-08
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2014-10-05
    • 2021-07-23
    • 2021-12-29
    相关资源
    最近更新 更多