【问题标题】:I am looking for a quick way to retrieve values from a dictionary in templates我正在寻找一种从模板中的字典中检索值的快速​​方法
【发布时间】:2017-10-03 05:16:50
【问题描述】:

我有以下情况:

{% if accounts.count > 0 %}
    {% for account in accounts %}
      <div>Balance:<b>{{ my_dict.account.id }}</b></div>
      <div><a href="/edit/{{ account.id }}"><button>Edit</button></a></div>
    {% endfor %}
{% else %}
    <p>...</p>
{% endif %}

.

这样安排就ok了

my_dict.account

但我会做这样的事情。我有两个点

my_dict.account.id

有没有办法做到这一点?在模板中创建一个变量是个好主意,但它对我不起作用

【问题讨论】:

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


【解决方案1】:

很高兴看到您的 my_dict 字典结构:什么是键(是帐户 ID 吗?)

可能是这样的:

my_dict[account.id]

尽管如果 my_dict 不知何故没有密钥,你会遇到错误。所以你可能想这样做:

my_dict.get(account.id, 'default value')

'default value' 是在 my_dict 中没有这样的键的情况下返回的值。

【讨论】:

    猜你喜欢
    • 2014-01-09
    • 2016-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多