hallazzang
hallazzang

Reputation: 701

Flask context processor doesn't work in an imported template

These are the codes I've wrote:

application.py:

from flask import Flask, render_template

app = Flask(__name__)

@app.context_processor
def inject_foo():
    return dict(foo='bar')

@app.route('/')
def index():
    return render_template('index.html')

index.html:

{% from 'macros.html' import print_foo %}
<p>print_foo: {{ print_foo() }}</p>
<p>foo(directly): {{ foo }}</p>

macros.html:

{% macro print_foo() %}
  foo is {{ foo }}
{% endmacro %}

And the files are structured like this:

flask-context-processor-issue/
    application.py
    templates/
        index.html
        macros.html

When I run the application(through flask run) and go to http://localhost:5000, I see this page:

print_foo: foo is
foo(directly): bar

foo for print_foo is missing. I think the reason is that foo is not visible inside the print_foo macro(which is in an imported template).

I can force foo to be globally visible by modify the application.py:

...
# @app.context_processor
# def inject_foo():
#     return dict(foo='bar')
app.jinja_env.globals['foo'] = 'bar'
...

But working along with app.context_processor is much general way I think, so I wonder is there any way to make the example works(with app.context_processor).

Waiting for your answer, thanks.

Upvotes: 3

Views: 3204

Answers (1)

hallazzang
hallazzang

Reputation: 701

After looking closer at the documentation(http://flask.pocoo.org/docs/0.12/templating/#context-processors), I've found that this should work:

index.html:

{% from 'macros.html' import print_foo with context %}
...

instead of

{% from 'macros.html' import print_foo %}
...

Dumb me.

Upvotes: 12

Related Questions