Accessing an array list in a Django jinja2 template

Accessing an array list in a Django jinja2 template

Using the dot notation in templates instead of square brackets

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.