在flask中返回render_templates和jinja templtes之间的区别

时间:2018-06-17 22:03:03

标签: python flask

我已经看到了两种在Flask中路由HTML页面的方法。

要么像这样声明一个名为模板的变量

def home():
    template = jinja_env.get_template('hello_form.html')
    return template.render()

或者您只是返回HTML模板

def home():
    return render_template('home.html', posts=posts)

两者之间是否存在差异,如果是,是什么?

1 个答案:

答案 0 :(得分:2)

他们实际上是相同的东西,你应该使用第二个,因为它更多" Flask-y"并且可以广播关于模板渲染的事件(尽管,很可能,你实际上并不关心这些事件)。

在Flask中,render_template is defined as

def render_template(template_name_or_list, **context):
    """Renders a template from the template folder with the given
    context.
    :param template_name_or_list: the name of the template to be
                                  rendered, or an iterable with template names
                                  the first one existing will be rendered
    :param context: the variables that should be available in the
                    context of the template.
    """
    ctx = _app_ctx_stack.top
    ctx.app.update_template_context(context)
    return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list),
                   context, ctx.app)

第一个参数是略微more abstract version of jinja_env.get_template。同样,context是可从模板访问的命名变量。最后,_render is defined right above为:

def _render(template, context, app):
    """Renders the template and fires the signal"""

    before_render_template.send(app, template=template, context=context)
    rv = template.render(context)
    template_rendered.send(app, template=template, context=context)
    return rv

第一行和第三行是广播模板正在呈现的事件。如果您有任何Flask扩展,他们可能正在监听这些事件并做更多的事情。最后,中间线与您自己称呼的template.render()完全相同。