【问题标题】:Iterate through dict keys in Django Templates遍历 Django 模板中的 dict 键
【发布时间】:2019-11-24 13:45:08
【问题描述】:

我有一个字典,我从我的视图传递给我的模板,但我无法让字典正确显示数据,如果有的话。字典如下:

context_dct = {

    'product0': {
        'totalentries': '6', 
        'type': 'hammers', 
        'brandname': 'DEWALT', 
        'price': '$25.84'}, 

    'product1': {
        'totalentries': '5', 
        'type': 'hammers', 
        'brandname': 'DEWALT', 
        'price': '$25.84'}, 

    'product2': {
        'totalentries': '8', 
        'type': 'hammers', 
        'brandname': 'DEWALT', 
        'price': '$25.84'}
}

使用 django 2.2 和 python3,我通过 render() 将 dict 传递给我的模板,并尝试像这样访问它:

<h1>Results:</h1>
{% for key, value in context_dct.items %}
    <h1>{{ key }}</h1>
    <h1>{{ value }}</h1>
    </br>
{% endfor %}

但唯一显示的是 h1 标签中的“结果”。我还尝试了其他几种访问字典的方法,类似于普通的 python 字典访问,但​​无济于事。当我不使用嵌套字典时,我可以让它正常工作,但是以这种方式使用它,我无法让它工作。我这里有什么遗漏吗?

【问题讨论】:

    标签: django python-3.x django-templates


    【解决方案1】:

    您需要将您的字典封装到另一个字典中,为其命名,例如:

    def some_view(request):
        # ...
        return render(request, 'some_template.html', { 'context_dct': context_dct })

    否则,您定义了 product0product1 等变量。

    【讨论】:

    • 好极了,它有效。我可以问一下,为什么这行得通?我不完全理解这里发生了什么。我希望这不是一个问题。
    • @data_the_goonie:字典将模板中的变量名称映射到内容。如果您直接传递context_dct,它会将product0 映射到该字典等。但是您希望将字典作为变量本身访问,因此我们可以通过构建映射'context_dct'(名称)的字典来解决此问题到内容。
    • 一旦我将每个单独的键值放入模板中,我将如何访问它?我现在可以让它们迭代地打印出来,但我希望能够单独操作它们。
    • @data_the_goonie:你也可以在字典中传递它们,写成{ 'context_dct': context_dct, **context_dct }
    猜你喜欢
    • 2016-01-16
    • 2018-03-16
    • 2010-11-04
    • 2019-01-08
    • 2018-05-24
    • 2016-11-12
    • 2021-01-17
    • 2017-08-13
    • 2016-08-13
    相关资源
    最近更新 更多