pv6142
pv6142

Reputation: 61

Access variable inside Jinja2 include

I am including a template in my base template, which the template I render extends. I set a variable in the direct template and try to use it in the included template. I would expect the following to output Active, but instead there's no output. Why can header.html not see the variable active?

main.py

@app.route("/")
def root():
    return render_template("page.html")

page.html

{% set active = True %}
{% extends "base.html" %}

base.html

{% include "header.html" %}

header.html

{% if active %}Active{% endif %}

Upvotes: 4

Views: 1837

Answers (1)

pv6142
pv6142

Reputation: 61

It appears to be a bug, as set out at https://github.com/mitsuhiko/jinja2/issues/352.

A workaround involves accessing the variable before the include.

base.html

<!-- {{ active }} -->
{% include "header.html" %}

Upvotes: 2

Related Questions