hal*_*ang 2 python jinja2 flask
这些是我写的代码:
应用程序.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')
Run Code Online (Sandbox Code Playgroud)
索引.html:
{% from 'macros.html' import print_foo %}
<p>print_foo: {{ print_foo() }}</p>
<p>foo(directly): {{ foo }}</p>
Run Code Online (Sandbox Code Playgroud)
宏.html:
{% macro print_foo() %}
foo is {{ foo }}
{% endmacro %}
Run Code Online (Sandbox Code Playgroud)
这些文件的结构如下:
flask-context-processor-issue/
application.py
templates/
index.html
macros.html
Run Code Online (Sandbox Code Playgroud)
当我运行应用程序(通过flask run)并转到 时http://localhost:5000,我看到此页面:
print_foo: foo is
foo(directly): bar
Run Code Online (Sandbox Code Playgroud)
foo因为print_foo不见了。我认为原因是宏foo内部不可见print_foo(在导入的模板中)。
我可以foo通过修改以下内容强制全局可见application.py:
...
# @app.context_processor
# def inject_foo():
# return dict(foo='bar')
app.jinja_env.globals['foo'] = 'bar'
...
Run Code Online (Sandbox Code Playgroud)
但是app.context_processor我认为与 with 一起工作是一种非常普遍的方式,所以我想知道有什么方法可以使示例工作(与app.context_processor)。
等待您的答复,谢谢。
在仔细查看文档(http://flask.pocoo.org/docs/0.12/templating/#context-processors)后,我发现这应该有效:
索引.html:
{% from 'macros.html' import print_foo with context %}
...
Run Code Online (Sandbox Code Playgroud)
代替
{% from 'macros.html' import print_foo %}
...
Run Code Online (Sandbox Code Playgroud)
哑我。
| 归档时间: |
|
| 查看次数: |
2129 次 |
| 最近记录: |