1
這是我寫的代碼:瓶上下文處理器不會在導入模板工作
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 %}
並且這些文件的結構是這樣的:
flask-context-processor-issue/
application.py
templates/
index.html
macros.html
當我運行應用程序(通過flask run
)和去http://localhost:5000
,我看到這個頁面:
print_foo: foo is
foo(directly): bar
foo
爲print_foo
不見了。我認爲原因是在print_foo
宏(它在導入的模板中)內foo
不可見。
我可以強制foo
是全局可見通過修改application.py
:
...
# @app.context_processor
# def inject_foo():
# return dict(foo='bar')
app.jinja_env.globals['foo'] = 'bar'
...
但隨着app.context_processor
是我想象的要普遍的方式,所以我不知道工作是有什麼辦法讓這個例子工程(含app.context_processor
)。
等待您的回答,謝謝。