Jinja2 inheritance is a feature that allows templates to share common structures and content, promoting code reuse and maintainability. Here's how it works:
base.jinja2
.{% block block_name %}{% endblock %}
placeholders to mark sections that child templates can override or extend.base.jinja2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}Default Title{% endblock %}</title>
</head>
<body>
<header>
<h1>Website Header</h1>
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>
</header>
<main>
{% block content %}
<p>This is the default content. Override this in child templates.</p>
{% endblock %}
</main>
<footer>
<p>© 2025 FooBar</p>
</footer>
</body>
</html>
{% extends 'base.jinja2' %}
directive.{% block block_name %}{% endblock %}
in the child template.child.jinja2
{% extends 'base.html' %}
{% block title %}Custom Title{% endblock %}
{% block content %}
<p>This is the custom content for this page.</p>
{% endblock %}
{% extends %}
directive ensures that the child template uses the structure of the base template. This inheritance mechanism helps streamline template management by separating concerns, such as defining the overall layout in the base template and customizing specific sections in child templates.
Render the template:
@onready var JINJA_ENV: Jinja2Environment = Jinja2Environment.new()
[...]
JINJA_ENV.set_base_directory("res://web/test/")
[...]
var tmpl: Jinja2Template = JINJA_ENV.get_template("child.jinja2")
var html: String = tmpl.render(params)
For more information about Jinja2, you can search for tutorials on the internet, as well as find many existing Jinja2 themes for inspiration.