Jinja Literal Expression: Tuples
n
(...)). The key difference between a tuple and a list is that a tuple is immutable, meaning its contents cannot be changed after it is created. Tuples are generally used to represent a fixed collection of related items, such as the coordinates of a point or a key-value pair. If a tuple contains only a single item, it must be followed by a comma to be correctly identified as a tuple (e.g., ('1-tuple',)).nn
nn
How It Works
nJinja2 recognizes any sequence of values within parentheses as a tuple. Tuples are often used when you need to group related pieces of data that should not be changed, such as the href and caption for a navigation link. While lists are best for collections where items might be added or removed, tuples are ideal for fixed data structures.nnA common use for tuples is to store a fixed number of items that can be unpacked into variables in a for loop.n
Syntax
n
{{ ('item1', 'item2', 'item3') }}n{% set my_tuple = (1, 2, 3) %}
nn
nn
Demonstration with Code Samples
nHere are some practical examples of how to use tuple literals in a Jinja2 application.n
1. Using Tuples in a `for` Loop
nThis is a powerful and common use case for tuples, especially when iterating over a list of structured data like navigation links. By using tuples, you ensure that the data for each link remains fixed and consistent.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. The `for` loop unpacks each tuple into the `href` and `caption` variables for each iteration. The immutability of the tuples ensures that the link data remains consistent throughout the loop.nn
nn
2. Creating a Single-Item Tuple
nThis example shows the special syntax required to create a tuple with only one element.nnJinja2 Templaten
{% set my_one_item_tuple = ('tuple',) %}n<p>Type of 'my_one_item_tuple' is: {{ my_one_item_tuple.__class__.__name__ }}</p>n{% set not_a_tuple = ('string') %}n<p>Type of 'not_a_tuple' is: {{ not_a_tuple.__class__.__name__ }}</p>
nExplanation: To create a tuple with a single item, you must include a trailing comma inside the parentheses. If you omit the comma, Jinja2 will treat the expression as a simple string or other data type, as demonstrated in the `not_a_tuple` example.nn
