Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template loop over dictionary.items with "items" as key

I have a dictionary in my template that I want to loop through in the usual way

{% for key, value in dictionary.items %}

But in dictionary I have a key called 'items', so my loop return the value of dictionary['items'] and tries to unpack the result as key, value.

How can I tell Django to use the function items instead of accessing the key?

like image 304
olofom Avatar asked Mar 14 '13 17:03

olofom


People also ask

How do you loop a dictionary in a Django template?

To iterate through dictionary in a dictionary in a Python Django template, we can loop through the items with a for loop. to loop through the data dict's entries with a for loop. We get the key value pairs with data.

How do I loop a list in a Django template?

Loop through multiple lists If you want to send multiple lists to Django template, it is advisable to use zip function and convert it into a tuple of lists before sending them in your response. Here is an example. zip function above packs all the lists into a single list of tuples (ID, name, age).

What does {% %} mean in Django?

{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.

What does {% include %} do?

{% include %} Processes a partial template. Any variables in the parent template will be available in the partial template. Variables set from the partial template using the set or assign tags will be available in the parent template.


1 Answers

Call dictionary.iteritems instead? I don't think there's a better way.

If you have no control over dictionary keys, the only safe way is a custom tag for iterating over dicts.

like image 176
Pavel Anossov Avatar answered Sep 28 '22 11:09

Pavel Anossov