Jason
Jason

Reputation: 52523

Access global variable inside Jinja2 include

I have a template like so:

{% extends 'master.html' %}
{% set myVar = true %}

...

{% block myBlock %}
    {% include '/includes/myinclude.html' %}
{% endblock %}

I am unable to access myVar inside of my include. However, if I do this:

{% block myBlock %}
    {% set myVar = myVar %}
    {% include '/includes/myinclude.html' %}
{% endblock %}

magically, it's accessible. Obviously I don't want to have to set my variables in two different places. What am I doing wrong, or is this just a dumb thing that Jinja2 does?

Upvotes: 1

Views: 993

Answers (1)

voscausa
voscausa

Reputation: 11706

I think you have to add scoped to the block, like:

{% block myBlock scoped %}
    {% include '/includes/myinclude.html' %}
{% endblock %}

From the doc: per default blocks may not access variables from outer scopes.

Upvotes: 1

Related Questions