Templates
Jinja Blocks
Defining Template Blocks
Jinja blocks use {% block %} for overridable content sections.
Introduction to Jinja Blocks
Jinja blocks are a powerful feature that allows you to define sections of a template that can be overridden by child templates. This is a key concept in template inheritance, enabling developers to create flexible and maintainable templates.
Basic Syntax of Jinja Blocks
Blocks in Jinja are defined using the {% block block_name %}
and {% endblock %}
tags. The block_name
is an identifier for the block, which can be used to reference it in child templates.
Here is a basic example of a block:
Overriding Blocks in Child Templates
In child templates, you can override blocks defined in the parent template. This is done by using the same {% block %}
tags with the same block name. The content inside these tags will replace the content of the corresponding block in the parent template.
Here's how you might override the blocks defined above:
Using Super to Extend Parent Blocks
Sometimes, you might want to add content to a block rather than completely replace it. Jinja provides the super()
function, which allows you to include the content of the parent block within the child block.
Here is an example of how you can use super()
:
Conclusion
Jinja blocks are a fundamental tool in template inheritance, allowing you to create templates that are both flexible and maintainable. By understanding how to define, override, and extend blocks, you can build complex templates with ease.
Templates
- Previous
- Template Inheritance
- Next
- Includes