Jinja Literal Expression: Integers
n
_) can be used as a visual separator for large numbers, similar to how commas are used in written language.nn
nn
How It Works
nJinja2 treats any sequence of digits as an integer. A number with a decimal point is treated as a float. The underscore character is ignored by the Jinja2 parser, so a number like 123_456 is treated as an integer 123456. This is incredibly useful for writing large numbers in a way that is easy for humans to read, without affecting the numerical value in any way.nnIntegers can be used in various parts of a template, including:n
- n
- For direct output using
{{ ... }}. - As the value for a variable using
{% set ... %}. - In arithmetic operations like addition (
+), subtraction (-), and division (/or//). - In conditional statements (e.g.,
{% if count > 10 %}).
n
n
n
n
n
Syntax
n
{{ 42 }}n{{ 123_456 }}n{% set page_size = 10 %}
nn
nn
Demonstration with Code Samples
nHere are some practical examples of how to use integer literals in a Jinja2 application.n
1. Using Integers in Arithmetic
nThis demonstrates a simple division operation where the `_` separator is used to make the numbers easier to read. The result is calculated correctly, as the underscores are ignored.nnJinja2 Templaten
{% set total_population = 7_900_000_000 %}n{% set total_countries = 195 %}n<p>Average population per country: {{ total_population // total_countries }}</p>
nExplanation: The template divides the total population by the number of countries, using the `//` operator for integer division. The underscores in the `total_population` variable do not affect the calculation, but they make the large number much easier to read in the code. The output will be the integer result of the division.nn
nn
2. Using an Integer in a Conditional Statement
nIntegers are frequently used to control template flow, for example, to display a message based on the number of items in a list.nnJinja2 Templaten
{% set item_count = 0 %}n<ul>n <!-- Assume a loop would go here to render items -->n</ul>n{% if item_count == 0 %}n <p>There are no items in your cart.</p>n{% endif %}
nExplanation: The template checks if the integer `item_count` is exactly `0`. If this condition is met, the message “There are no items in your cart.” is rendered.nn
nn
3. Working with Integers from a Loop
nThis example shows a combination of a loop and integer arithmetic to display the total price of a list of products, where the price is an integer.nnJinja2 Templaten
{% set products = [{ 'name': 'Laptop', 'price': 1500 }, { 'name': 'Mouse', 'price': 50 }] %}n{% set total_price = 0 %}n{% for product in products %}n {% set total_price = total_price + product.price %}n{% endfor %}n<p>Total order price: ${{ total_price }}</p>
nExplanation: The template initializes a `total_price` variable to the integer `0`. It then iterates through the `products` list, adding the `price` of each product to the running total. The final result is the sum of all the integer prices.nn
