【问题标题】:Accessing a dictionary using a key from another dictionary in Django template使用Django模板中另一个字典中的键访问字典
【发布时间】:2018-11-15 11:12:44
【问题描述】:

我将两个字典传递给模板内的 Django 模板(reservationsprices)我有这样的东西:

{% for key,value in reservations.items %}
...
...
{% if value is False %}
        <div class="room">
            <p class="room-id">{{ prices.{{ key }} }}</p>
         </div>
{% else %}
...
...
{% endfor %}

现在的问题是这一行 {{ prices.{{ key }} }} 我正在尝试从要使用的预订字典中评估 key 值这 价格决定如何做到这一点?并提前感谢您。

【问题讨论】:

  • 抱歉浪费了您的时间,没有
  • 没有尝试,但 {{ prices.key }} 应该可以工作......并且请只发布可以复制粘贴和测试的代码:特别是还要发布示例输入字典。见minimal, complete, and verifiable example
  • 感谢您的建议,{{ prices.key }} 尝试在价格字典中查找关键属性。
  • 再次:发布输入字典:否则很难说出问题所在。
  • {{ 价格。{{ key }} }} 将不起作用。您需要传递 {{price.0}} 之类的密钥。

标签: python django dictionary


【解决方案1】:

仅适用于自定义模板标签,例如:

# access_tags.py

from django import template        

register = template.Library()


@register.filter(name='access')    
def access(value, arg):    
    return value.get(arg, value.get(unicode(arg), None))

在模板中:

{% load access_tags %}
...
<p class="room-id">{{ prices|access:key }}</p>
...

【讨论】:

  • ndpu 非常感谢,这正是我所需要的
猜你喜欢
  • 2019-09-01
  • 2021-04-10
  • 2015-09-28
  • 2013-11-13
  • 2016-11-26
  • 1970-01-01
  • 2021-10-17
相关资源
最近更新 更多