Rajat Gupta
Rajat Gupta

Reputation: 1959

Pass context to included Jinja Template in Jinja Template

I have common things in all Jinja files. I want to move all common content to one single Jinja file in Flask.

My app is written in Flask and I am passing context to Jinja template like

def f1(name): render_template('j1.jinja', name=name)

def f2(name): render_template('j2.jinja', name=name)

def f3(name): render_template('j3.jinja', name=name)

My j1.jinja file is:

{%block content %}
Name: {{ name }}
Hello
{% endblock %}

My j2.jinja file is:

{%block content %}
Name: {{ name }}
Bye
{% endblock %}

My j3.jinja file is:

{%block content %}
Name: {{ name }}
Howdy
{% endblock %}

I moved common content to single Jinja file common.jinja which is:

{% block content %}
Name : {{name}}
{% endblock %}

I am including it in all Jinja files like:

{% include 'common.jinja' with { "name": name } only %}

which doesn't work. I am getting the Exception:

Exception Occured. Explanation: expected token 'end of statement block', got 'with'

How can I pass context to included Jinja file?

Upvotes: 2

Views: 4765

Answers (1)

Zaur Nasibov
Zaur Nasibov

Reputation: 22659

Your code looks a bit weird. There is no separate with statement that specifies context, it is with context which is often used with import statement (see Import context behaviour).

To pass any context to an included template, simply render the parent template with context variables, e.g. in render_template():

render_template('j3.jinja', name=name)

Upvotes: 2

Related Questions