ITERATING OR DISPLAYING DICTIONARY ITEMS IN DJANGO TEMPLATES
Iterating over a dictionary in python templates is what we usually come across. In this section i have described how to iterate a dictionary and also what happens if its values are a tuple.
{% for key, val in dict.items %}
<td>{{ key }}</td>
<td>{{ val }}</td>
{% endfor %}
If the dictionary value contains a Tuple:
For example if your dictionary is like
{'title' : ('book','play'), title2' : ('book2','play2')}
Then play with the indices of tuples
for instance the book, book2 and play,play2 are at indices 0 and 1 respectively, so we can access their values in templates like described under
{% for key, val in dict.items %}This will display the key and against the key the values of tuples
<td>{{ key }}</td>
<td>{{ val.0 }}</td>
<td>{{ val.1 }}</td>
{% endfor %}
Now if you want to match a key by converting it in lowercase so use built-in template tag for this purpose
if you have a template variable name then it can be converted to lowercase by using lowerfilter
{{ name | lower }}There are many built-in templates for django which can be found at
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocsYou can also make your custom template tags. I will be publishing a post in near future guiding you about making the custom template tags
No comments:
Post a Comment