Jinja Block Assignments Introduction
n
Jinja’s block assignment feature allows you to capture a multi-line block of content and assign it to a variable. This is a powerful and elegant solution for creating multi-line strings, which is a common task in templates and can be cumbersome with single-line assignments. The block assignment is a great alternative to Python’s triple quotes, making your template code cleaner and more readable.
nn
How It Works
n
To use a block assignment, you start with {% set variable_name %} and end with {% endset %}. Everything in between these tags, including newlines and white space, is captured and assigned to the variable. This allows you to define a block of HTML, a multi-line string, or any other content in a structured way.
nn
Basic Usage
n
{% set navigation %}n <li><a href="/">Index</a>n <li><a href="/downloads">Downloads</a>n{% endset %}nn<ul>n{{ navigation }}n</ul>
n
In this example, the entire li block is captured and stored in the navigation variable. When the template is rendered, {{ navigation }} will be replaced with the full block of HTML, making it easy to embed into an unordered list.
nn
nn
Practical Use Cases
n
Block assignment is useful for a variety of tasks:
nn
- n
- n
- n
- Multi-line strings: Easily define text with line breaks for things like copyright notices or long descriptions.
- Reusable HTML snippets: Capture a complex HTML structure that you’ll use in multiple places on the same page.
- Injecting content into other blocks: You can assign a content block to a variable and then pass it to a macro or include it in a parent template.
n
n
n
n
n
n
This feature provides a clean and readable way to manage complex data and content within your templates.
nn
n
n
