【问题标题】:How to display the value of key in dictionary in jinja2 template?如何在jinja2模板中显示字典中键的值?
【发布时间】:2019-02-20 12:14:56
【问题描述】:

我想在 django 模板中显示字典的特定键的值。

dict1 = {'Device.Bridging.': '0', 'Device.': '0', 'Device.XMPP.SupportedServerConnectAlgorithms': '0'}

例如:我想显示键“Device.XMPP.SupportedServerConnectAlgorithms”的值


这就是我尝试访问该值的方式。

<div>
<p>{{dict1.Device.XMPP.SupportedServerConnectAlgorithms}}</p>
</div>

但是上面的代码给出的是空值。

<div>
<p>{{dict1["Device.XMPP.SupportedServerConnectAlgorithms"]}}</p>
</div>


Exception Type:     TemplateSyntaxError
Exception Value:    

Could not parse the remainder: '["Device.XMPP.SupportedServerConnectAlgorithms"]' from 'pvals["Device.XMPP.SupportedServerConnectAlgorithms"]'

【问题讨论】:

  • 你没有使用 Jinja2。您正在使用 Django 模板语言。
  • 我想你可以在这里找到解决方案:stackoverflow.com/questions/11801061/…
  • @DanielRoseman 我已经更新了,谢谢
  • @SergeyPugach 我尝试了您共享的链接中提供的解决方案,但出现以下错误。无法解析剩余部分:来自 'pvals["Device.XMPP.SupportedServerConnectAlgorithms"]' 的 '["Device.XMPP.SupportedServerConnectAlgorithms"]'
  • 那你根本没有关注 Sergey 的链接。

标签: django python-3.x


【解决方案1】:

您应该将上下文字典发送到模板

views.py

from django.shortcuts import render

def index(request):
    dict1 = {
        'test_var': 'test0',
    }

    return render(request, 'test_template.html', dict1)

模板/test_template.html:

<div>
    <p>
        {{ test_var }}
    </p>
</div>

# 输​​出:

test0

编辑: 您不能在变量中使用 .。 (尝试使用下划线)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-24
    • 1970-01-01
    • 2014-02-08
    • 2011-12-06
    • 1970-01-01
    • 2016-09-22
    • 2013-11-24
    • 2020-08-27
    相关资源
    最近更新 更多