Skip to main content

Command Palette

Search for a command to run...

Accessing an array list in a Django jinja2 template

Using the dot notation in templates instead of square brackets

Updated
โ€ข1 min read
Accessing an array list in a Django jinja2 template
A
I am a web developer from Navi Mumbai. Mainly dealt with LAMP stack, now into Django and getting into Laravel and Cloud. Founder of nerul.in and gaali.in

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.