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.

0
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