zhangailin
zhangailin

Reputation: 976

Jinja: How to override variables in super block?

I've got a template parent.tpl:

{% set myvar = 'AAA' %}

{% block par %}
{{ myvar }}
{% endblock %}

and a child.tpl

{% extends "parent.tpl" %}

{% block par %}
{% set myvar = 'BBB' %}
{{ super() }}
{% endblock %}

the child.tpl results:

AAA

but not

BBB

How can I get BBB output with variable override?

Thanks

Upvotes: 7

Views: 4052

Answers (2)

Certitude
Certitude

Reputation: 91

Use namespaces:

parent.tpl:

{% set ns=namespace(myvar = 'AAA') %}

{% block par %}
{{ ns.myvar }}
{% endblock %}

child.tpl:

{% extends "parent.tpl" %}

{% block par %}
{% set ns.myvar = 'BBB' %}
{{ super() }}
{% endblock %}

Upvotes: 0

Igor Hatarist
Igor Hatarist

Reputation: 5442

If you're using Flask, you can use a global variable like g.myvar. It will be available in every template.

Take a look at Pass variables from child template to parent in Jinja2.

Upvotes: 2

Related Questions