url_for无法在jinja2模板中运行,给出“未定义”错误

时间:2017-08-02 18:09:59

标签: templates flask jinja2

我是Flask的新手并尝试使用Jinja2创建布局模板。

    <!DOCTYPE html>
    <html lang="en">
    <head>
       <meta charset="UTF-8">
       <link href="{{ url_for('static', filename='bundle/login.styles.css') }}" rel="stylesheet">
       <title>{{meta['title']}}</title>
   </head>
   <body>
       <div class="app" id="app">
          {% block content %}
          {% endblock %}
       </div>
       <script type="text/javascript" src="{{ url_for('static', filename='bundle/login.bundle.js') }}"></script>
   </body>
   </html>

问题是,当我使用jinja2.exceptions.UndefinedError时,我收到错误template.render()

    jinja2.exceptions.UndefinedError: 'url_for' is undefined 

虽然我使用render_template()时工作正常。没有生成错误。我不知道我做错了什么。

此外,使用Jinja2.Environmentjinga.get_template()生成模板与使用render_template()

之间的区别是什么?

1 个答案:

答案 0 :(得分:1)

使用render_template()时,还会将url_for()函数添加到模板中可用的全局变量中。

http://flask.pocoo.org/docs/0.12/templating/#standard-context

如果你没有那样做,那么它将无法使用。

如果你想了解一下这个特定问题的起点可能就在这里:

https://github.com/pallets/flask/blob/master/flask/templating.py#L121

https://github.com/pallets/flask/blob/master/flask/app.py#L699

相关问题