【发布时间】:2014-02-26 14:19:54
【问题描述】:
在我的第一个 Flask 项目中工作时,我在尝试从 Jinja2 模板渲染宏时偶然发现了 jinja2.exceptions.UndefinedError 异常。事实证明,Jinja2 在尝试解析模板的其余部分确实包含对全局请求对象的引用时会生成此异常。
这是我用于测试用例的模板 test.html:
<!doctype html>
{% macro test_macro() -%}
Rendered from macro
{%- endmacro %}
{{ request.authorization }}
Flask 代码#1:渲染模板(成功):
@app.route("/test")
def test_view():
return render_template('test.html')
Flask 代码 #2:渲染宏(失败):
@app.route("/test")
def test_view():
test_macro = get_template_attribute('test.html', 'test_macro')
return test_macro()
如果您从模板中取出{{ request.authorization }},则第二次测试将成功执行。
烧瓶代码#3:使用workaround I found in the Flask mailing list archive(成功):
@app.route("/test")
def test_view():
t = app.jinja_env.get_template('test.html')
mod = t.make_module({'request': request})
return mod.test_macro()
虽然我现在有一个工作代码,但不知道为什么第二种方法会失败,我觉得很不舒服。为什么 Jinja2 只需要渲染宏时还要关心模板的其余部分?
【问题讨论】: