Applying Filters to Multi-line Block Assignments
n
In Jinja2, you can apply filters to a variable created with a block assignment. This allows you to process the entire captured block of content, including multiple lines and dynamic variables, before it’s assigned to the variable. This is a powerful and efficient way to transform text and content without having to process it after the assignment has been made.
nn
How It Works
n
To apply a filter to a block assignment, you simply add the filter after the variable name, just as you would with a single-line assignment. Jinja will capture the content of the block, apply the specified filter(s), and then assign the final, filtered content to the variable.
nn
Basic Usage
n
{% set reply | wordwrap %}n You wrote:n {{ message }}n{% endset %}
n
In this example, the entire block—including the static text “You wrote:” and the dynamic content from the `message` variable—is captured. The `wordwrap` filter is then applied, which wraps long lines of text to fit within a specified width. The result is stored in the `reply` variable, ready to be used in your template.
nn
nn
Chaining Filters and Arguments
n
You can also **chain multiple filters** and include **arguments** to customize their behavior, just as you would with other filter applications.
nn
Example with Chained Filters
n
{% set final_content | striptags | truncate(100) %}n <p>Hello <strong>{{ user.name }}</strong>, here is some important information.</p>n <p>This text will be stripped of HTML and then truncated to 100 characters.</p>n{% endset %}nn<p>{{ final_content }}</p>
n
Here, the striptags filter runs first, followed by the truncate filter with the argument 100. The final, processed string is then assigned to the `final_content` variable.
nn
n
n
