How to use django template dot notation inside a for loop

£可爱£侵袭症+ 提交于 2019-12-06 11:35:23

问题


I am trying to retrieve the value of a dictionary key and display that on the page in a Django template:

{% for dictkey in keys %}
    <p> {{ mydict.dictkey }} </p>
{% endfor %}

(let's say 'keys' and 'mydict' have been passed into the template in the Context)

Django renders the page but without the dictionary contents ("Invalid template variable")

I assume the problem is that it is trying to do mydict['dictkey'] instead of mydict[actual key IN the variable dictkey]? How does one "escape" this behavior?

Thanks!

UPDATE: Based on the answers received, I need to add that I'm actually looking specifically for how to achieve a key lookup inside a for loop. This is more representative of my actual code:

{% for key, value in mydict1.items %}
    <p> {{ mydict2.key }} </p>
{% endfor %}

Basically, I have two dictionaries that share the same keys, so I can't do the items() trick for the second one.


回答1:


See this answer to a (possibly duplicate) related question.

It creates a custom filter that, when applied to a dictionary with a key as it's argument, does the lookup on the dictionary using the key and returns the result.

Code:

@register.filter
def lookup(d, key):
    if key not in d:
        return None
    return d[key]

Usage:

{% for dictkey in dict1.keys %}
    <p> {{ dict2|lookup:dictkey }} </p>
{% endfor %}

Registering the filter is covered in the documentation.

I find it sad that this sort of thing isn't built in.




回答2:


From http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for

This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data, the following would display the keys and values of the dictionary:

{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}

The trick is that you need to call dict.items() to get the (key, value) pair.




回答3:


See the docs: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for

{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}


来源:https://stackoverflow.com/questions/4363032/how-to-use-django-template-dot-notation-inside-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!