【问题标题】:How to access a dictionary element in django template?如何访问 django 模板中的字典元素?
【发布时间】:2014-09-10 03:05:13
【问题描述】:

我在 django 模板中有一个名为 income 的字典,我的模板中还有一个名为 factors 的列表,我想要这样的东西:

{% for factor in factors%}
<div> {{ income[factor.id] }} </div>
{% endfor %}

但是 {{ income[factor.id] }} 是错误的,我该怎么做?

【问题讨论】:

    标签: python django dictionary django-templates


    【解决方案1】:

    你可以这样写一个模板标签:

    @register.filter
    def get_value(d, key):
        return d.get(key)
    

    并像这样使用它:

    {{ income|get_value:factor.id }}
    

    【讨论】:

      【解决方案2】:

      编辑:正如@kbnk 所指出的,我弄错了,这不起作用。

      如果您不想创建过滤器,可以尝试以下方法:

      {% for factor in factors %}
          {% with factor_id=factor.id %}
              <div> {{ income.factor_id] }} </div>
          {% endwith %}
      {% endfor %}
      

      这很有效,因为您可以在 django 模板中进行字典类型的查找。查看 django 模板文档了解更多详情:https://docs.djangoproject.com/en/dev/ref/templates/api/#variables-and-lookups

      【讨论】:

      • 这行不通,因为模板会将文字字符串 'factor_id' 作为字典键,而不是 factor_id 变量的值。
      • @kbnk:我能做些什么来解决这个问题并使用这个方法吗?我不想为此创建过滤器
      • @Navid777 您可以通过在视图代码中以某种方式重构incomefactors 来解决它,否则您需要一个模板过滤器。
      猜你喜欢
      • 2017-03-09
      • 2014-10-05
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      • 2011-07-11
      • 2021-10-17
      相关资源
      最近更新 更多