Jinja Literal Expression: Lists
n
[...]). Lists are useful for storing sequential data that you need to iterate over, such as a collection of items, user accounts, or navigation links. Lists are also mutable, meaning you can change their contents.nn
nn
How It Works
nJinja2 recognizes any sequence of values within square brackets as a list. Lists can hold a mix of different data types, including strings, numbers, booleans, and even other lists or tuples. A key feature of lists is that they are ordered, meaning you can access elements by their index, starting from 0.nnLists are most commonly used in conjunction with a for loop to iterate through each item and perform an action, such as displaying each item as a list entry or building a navigation menu.n
Syntax
n
{{ ['item1', 'item2', 'item3'] }}n{% set my_list = [1, 2, 3] %}
nn
nn
Demonstration with Code Samples
nHere are some practical examples of how to use list literals in a Jinja2 application.n
1. Using a List in a `for` Loop
nThis is a powerful and common use case for lists, particularly when iterating over a collection of data, such as a set of links.nnJinja2 Templaten
<ul>n{% for href, caption in [('index.html', 'Index'), ('about.html', 'About'), ('downloads.html', 'Downloads')] %}n <li><a href="{{ href }}">{{ caption }}</a></li>n{% endfor %}n</ul>
nExplanation: This template iterates over a list of tuples. In each iteration, it unpacks the tuple into the `href` and `caption` variables. It then uses these variables to create an HTML list item with a link, demonstrating how you can build dynamic content from a list of structured data.nn
nn
2. Accessing List Elements by Index
nYou can retrieve individual elements from a list by specifying their index. Remember that indexing is zero-based.nnJinja2 Templaten
{% set fruits = ['apple', 'banana', 'cherry'] %}n<p>The first fruit is: {{ fruits[0] }}</p>n<p>The last fruit is: {{ fruits[-1] }}</p>
nExplanation: This example shows how to access the first element using `[0]` and the last element using the negative index `[-1]`. The output will be the values “apple” and “cherry”, respectively.nn
nn
3. Storing Different Data Types
nA single list can hold a variety of data types, making it a flexible container for a collection of related values.nnJinja2 Templaten
{% set profile_data = ['John Doe', 30, True, 'New York'] %}n<ul>n <li>Name: {{ profile_data[0] }}</li>n <li>Age: {{ profile_data[1] }}</li>n <li>Is Active: {{ profile_data[2] }}</li>n <li>City: {{ profile_data[3] }}</li>n</ul>
nExplanation: The `profile_data` list contains a string, an integer, a boolean, and another string. The template then accesses and displays each item by its index, showing how a list can be used to store and present a simple record of information.nn
