levant pied
levant pied

Reputation: 4501

Change variable in included jinja2 template

Say I have two templates:

main.j2

{% include "vars.j2" %}

main: {{ var1 }}

vars.j2

{% set var1 = 123 %}

vars: {{ var1 }}

When run, only this line is output:

vars: 123

i.e. var1 is undefined in main.j2, even though it gets set to a value in the included vars.j2 template.

How can I pass variables from included template back to template that includes it? I considered chaining extends, but wondered if there's a more elegant approach.

Upvotes: 2

Views: 1696

Answers (2)

Eric Negaard
Eric Negaard

Reputation: 11

I recently had a need to do the same thing, and found 2 solutions.

If you have Jinja version 2.10 or later, namespaces can be used:

main_ns.j2:

{% set ns = namespace() %}
{% include "vars_ns.j2" %}
main_ns: {{ ns.var1 }}

vars_ns.j2:

{% set ns.var1 = 123 %}
vars_ns: {{ ns.var1 }}

In Jinja 2.2 or later, it can be accomplished with block scoping of variables. I put the variable settings in the base template so that multiple children can extend it.

vars_block.j2:

{% set var1 = 123 %}
vars_block: {{ var1 }}
{% block content scoped %}{% endblock %}

main_block.j2:

{% extends "vars_block.j2" %}
{% block content %}
main_block: {{ var1 }}
{% endblock %}

Upvotes: 1

jrbedard
jrbedard

Reputation: 3730

You can try using with:

{% with var1=0 %}
    {% include "vars.j2" %}
    vars: {{ var1 }}
{% endwith %}

Upvotes: 0

Related Questions