'Jinja 2 - Include a variable template in a layout template

I would like to create a variable template with j2 and include this template in all my layout templates. It would act like a config template where all my required variables are defined with default.

Here is the content of `variables.j2``

{% set locale = "en" %}

then `layout.j2``

{% include "variables.j2" %}

{% block title %} default title {% endblock title %}

and my page.j2

{% extends "layout.j2" %}
{% if locale == "en" %}
Hello
{% else %}
Guten Tag
{% endif %}

With this code I got this error jinja2.exceptions.UndefinedError: 'locale' is undefined



Solution 1:[1]

This method is not working because including a template means rendering the template and returning the output.

But there are alternative ways to achieve this goal. The first one is to move the variables to the base layout.j2 template. The child templates will receive the variables defined there.

The second and IMO recommended way is to use Jinja2's Environment.globals. This is a simple dict, the variables defined there are accessible by every template in the environment, so you can define your global variables at the application level. (If you are using Flask, its global functions are also defined here.)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Dauros