Filters
Jinja Filter Chaining
Chaining Filters
Jinja filter chaining applies sequential filters for complex output.
Understanding Jinja Filter Chaining
Jinja filter chaining is a powerful feature that allows you to apply multiple filters to a single variable or expression in a sequence. This enables you to transform and format data in a flexible and efficient manner within your template files.
Filter chaining works by taking the output of one filter and passing it as input to the next filter in the chain. This process continues until all specified filters have been applied, resulting in a final, processed output.
Basic Syntax for Filter Chaining
The basic syntax for chaining filters in Jinja involves using the pipe character |
to separate each filter. Here is the general format:
{{ variable | filter1 | filter2 | ... | filterN }}
Let's look at an example to illustrate this syntax.
In this example, the string " hello world " is first processed by the trim
filter, which removes any leading or trailing whitespace. The result is then passed to the capitalize
filter, which transforms the first character to uppercase. The output of this operation would be "Hello world".
Practical Example of Jinja Filter Chaining
Filter chaining is often used in real-world applications to format data for display. Consider an example where you want to format a number with thousands separators and round it to two decimal places:
In this example, the number 12345.6789
is first rounded to two decimal places using the round
filter. The result, 12345.68
, is then converted to a string so that the replace
filter can replace the decimal point with a comma, resulting in "12345,68".
Combining Jinja Filters and Logic
Jinja filter chaining can also be combined with conditional statements for more advanced templating logic. This allows you to conditionally apply filters based on certain criteria. Here is a basic example:
In this example, the conditional statement checks if show_price
is true. If it is, the price
is converted to a float, rounded to two decimal places, and then converted to a string for display. If show_price
is false, the output "Price not available" is displayed instead.
Filters
- Previous
- Template Filters
- Next
- Tests