Jinja2 Operator: | (Pipe, Vertical Bar)
n
| operator, also known as the pipe or vertical bar, is used in Jinja2 to apply a filter to a value. Filters are functions that modify the value of a variable or expression before it is displayed. This operator is essential for formatting data, manipulating strings, and preparing variables for output directly within a template.nn
nn
How It Works
nThe pipe operator takes the output of the expression on its left and passes it as the first argument to the filter on its right. You can chain multiple filters together, with the output of one filter becoming the input for the next.n
Syntax
n
{{ value | filter_name }}
nFor filters that accept additional arguments, you pass them in parentheses just like a function call.n
{{ value | filter_name(arg1, arg2) }}
nn
nn
Demonstration with Code Samples
nHere are some practical examples of how to use the | operator and various filters.n
1. Formatting Strings
nFilters are commonly used to format strings, such as capitalizing the first letter or making the entire string uppercase.nnJinja2 Templaten
<p>Hello, {{ user.name|capitalize }}!</p>n<p>Your subscription status: {{ user.subscription_status|upper }}</p>
nExplanation: The capitalize filter ensures the user’s name starts with a capital letter, while the upper filter converts the subscription status to all uppercase letters for emphasis.nn
nn
2. Handling Numbers and Lists
nFilters can manipulate numbers for formatting and join list items into a single string.nnJinja2 Templaten
<p>Product Price: ${{ product.price|round(2) }}</p>nn<h3>Tags</h3>n<p>{{ product.tags|join(', ') }}</p>
nExplanation: The round filter formats the price to two decimal places. The join filter takes the items in the product.tags list and combines them into a single string, separated by a comma and a space.nn
nn
3. Chaining Multiple Filters
nYou can apply multiple filters sequentially by chaining the | operator.nnJinja2 Templaten
{% set welcome_message = 'welcome to our site' %}n<p>{{ welcome_message|title|reverse }}</p>
nExplanation: This example first applies the title filter to capitalize each word of the string ('Welcome To Our Site'), and then applies the reverse filter to reverse the order of the characters, resulting in a final output of 'etiS ruO oT emocleW'. The output of each filter becomes the input for the next.nn
