Jinja2 - import/include

2025-01-01

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 Template:

  1. Create a base template that defines the overall structure of the HTML document or page, in this case we will create a file called base.jinja2.
  2. This base template uses {% 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>&copy; 2025 FooBar</p>
</footer>
</body>
</html>

Child Template

  1. Create child templates that inherit from the base template using the {% extends 'base.jinja2' %} directive.
  2. Override specific blocks from the base template using {% 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 %}
  • The {% extends %} directive ensures that the child template uses the structure of the base template.
  • The overridden blocks replace the corresponding blocks in the base template.
  • Blocks that are not overridden will display their default content from 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.

Rendering

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)

More information

For more information about Jinja2, you can search for tutorials on the internet, as well as find many existing Jinja2 themes for inspiration.