访问具有django模板属性的字典?

时间:2018-12-31 02:32:39

标签: python django django-templates

所以我的问题是我需要遍历给定属性的字典,该属性是for循环的值。例如,我有一个名为my_dictionary的字典,该字典正在Django模板中的for循环进行迭代,并带有一个名为q的属性。我需要的是使用q属性访问该词典。我尝试使用{{my_dictionary.q}}{{my_dictionary.{{q}} }},但没有一个起作用。我能做什么?我猜应该和Python my_dictionary[q]中的类似。谢谢。

更新:实际上,qmy_dictionary无关。假设q是列表[1,2,3]的每个元素,而my_dictionary是具有以下形式的字典:{1: ['a','b','c'], 2:['a'], 3:['c']}。因此,我要尝试的是在给定第一个列表[1,2,3]的值的情况下访问字典的每个值。

2 个答案:

答案 0 :(得分:1)

假设您将字典从视图返回到模板。假设您的字典名称为my_dictionary,那么在模板中您需要这样做:

{% for q in my_dictionary %}
    <p> {{ q.your_dictionary_key_name }} </p>
{% endfor %}

用于遍历字典中的列表项

{% for key, value in dictionary.items %}
    <li><a href="{{key}}">{{value}}</a></li>
{% endfor %}

答案 1 :(得分:0)

您可以编写自定义模板过滤器:

from django.template.defaulttags import register
register = Library()
...
@register.filter
def get_item(dictionary, key):
    # use .get so that if the key does not exist a KeyError will be raised
    return dictionary.get(key)

在模板中的用法:

{% for q, value in my_dictionary.items %}
    {{ my_dictionary.items|get_item:<key_variable_here> }}
{% endfor %}