Accessing an array list in a Django jinja2 template
This may seem miniscule, but many newbies tend to forget the fact that template coding in HTML is not necessarily equivalent to language code.
In almost all programming languages (or probably all ?), we access an index of an array / list using the square brackets notation with the index number in between.
For example, in python code we would do :
fruits = ['๐', '๐', '๐']
print(fruits[1]) # will print ๐
In a Django, which uses Jinja2 templating by default, when we set the values in context and send it across to the template, we use dot followed by the index to access the array index like this :
{{ fruits.1 }}
So, if we have something like this which has the fruit and the price of it, in the context,
fruits = [['๐', 50], ['๐', 35], ['๐', 22]]
context = {'fruitsWithPrice': fruits}
then we would need to use fruit.0
and fruit.1
for each fruit.
{% for fruit in fruitsWithPrice %}
{{ fruit.0 }} - ${{ fruit.1 }}<br/>
{% endfor %}
This is something I myself didn't know for a while too.
Subscribe to my newsletter
Read articles from Anjanesh Lekshminarayanan directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Anjanesh Lekshminarayanan
Anjanesh Lekshminarayanan
I am a web developer from Navi Mumbai working as a consultant for cloudxchange.io. Mainly dealt with LAMP stack, now into Django and trying to learn Laravel and Google Cloud. TensorFlow in the near future. Founder of nerul.in