Data structure in Jinja

Use more complex data structures in Jinja to store large numbers of variables under a single name

Sometimes you need to store multiple values of the same type with the same usage. For example, you have a bunch of products that you want to show to a customer in an email. Creating a separate variable for each of them would be too much work.

That's why Jinja has more complex data structures for such cases. These data structures are a set of variables stored together under a single name. They also provide useful additional features. In this article, we'll demonstrate three of such structures and help you understand the key differences between them.

Lists

The simplest data structure in Jinja is a list. A list in Jinja is flexible, you don't need to know the number of elements it will have in advance. If you need to add more elements, the list will automatically expand.

What's more, you don't need to worry about the types of data that are stored in the list. Lists can contain any type of data, meaning you can mix different types of data in a single list.

Creating items in a list

To create a list in Jinja, use the notation {% set myList = %} . To create a list, use square brackets. Inside the brackets, specify the values separated by commas. You can also create an empty list by simply leaving the brackets empty.

An example of creating a list with items:

{% set numbersOneToFive = [1, 2, 3, 4, 5] %}

An example of creating an empty list:

{% set emptyList = [] %}


Accessing elements in a list

Lists in Jinja are indexed, which means that each element has its own ordinal number - an index. Indexes start with 0. This allows you to easily access any element of the list.

For example, let's create the following list:

{% set myList = ['a', 'b', 'c', 'x', 'k'] %}
  • 'a'  is the first element, its index is 0.
  • 'k' is the fifth element, its index is 4.

Use square brackets to get an element by its index.

  • The first element: {{ myList[0] }}  - returns 'a'.
  • The fifth element: {{ myList[4] }} - returns 'k'.

It is important to remember that indices start at 0, not 1. For example, myList[1] will return the second element, not the first.

Adding and Removing elements in a List

Since lists are dynamic data structures, you can add and remove elements in Jinja templates.

Adding an element to a list

To add an item to a list, use the  append  command:

{% set myList = ['a', 'b', 'c'] %}
{% append 'd' to myList %}

Element 'd'  will be added to the end of  myList .

Removing more than one element

The index function returns the index of the first occurrence of a value in a list. If the list may contain multiple identical values, or you are not sure that a value is in the list, use flow control or filtering.

{# Initialize myList with some values #}
{% set myList = [1, 5, 3, 4, 2] %}
{# add 5 to myList #}
{% append 5 to myList %}
{# remove the second element from the list #}
{% set temp = myList.pop(1) %}
{# find the index of the number 2 in myList #}
{% set myIndex = myList.index(2) %}
{# remove the number 2 from myList #}
{% set temp = myList.pop(myIndex) %}
{# print the list and the index of the number 1 #}
{{ "values in my list:"}}
{{ myList }}
{% set indexOne = myList.index(1) %}
{{ "</br> index of the number one:" }}
{{ indexOne }}

The output will be:

  • Values in the list: 1,3,4,5
  • Index of ‘1’: 0


Tuples

Tuples are another data structure in Jinja. They are similar to lists, but are immutable, meaning they cannot be changed once created. Tuples are read-only.

Creating a Tuple

Define a tuple using parentheses:

{% set myPair = ("dog", "cat") %}

This tuple contains two values:"dog"  and "cat" . Tuples are also indexed from 0.

Accessing tuple elements

To access the second element of "cat":

{{ myPair[1] }}

Creating a tuple with one element

If you want a tuple with one element, add a comma after the value:

{% set mySingleton = ("myString",) %}


Dictionaries

Dictionaries are another data structure in Jinja. They are similar to lists, but are used to store values as key-value pairs. Instead of indexes like lists, dictionaries use keys to access values.

Definition and Use of Dictionary

To create a dictionary, use curly braces:

{% set myDict = {"Animal": "Duck", "Breed": "American Pekin"} %}

Accessing Values

Use a key to get a value from a dictionary:

{{ myDict["Animal"] }} {# Returns "Duck" #}

For instance:

{% set myDict = {"Animal": "Duck", "Breed": "American Pekin"} %}
{{ myDict["Animal"] }} {# Outputs "Duck" #}

Please note: dictionary keys can be strings, as well as integers, floats, or even the None value.


Other articles on Jinja:

Basic Jinja Syntax
Filters in Jinja
Personalization with Jinja

Powered by