在flask中返回render_templates和jinja templtes之间的区别 [英] Difference between returning render_templates and jinja templtes in flask
问题描述
我已经看到了两种在Flask中路由HTML页面的方法.
I have seen two ways to route HTML pages in Flask.
要么像这样声明一个称为模板的变量
Either you declare a variable called template like so
def home():
template = jinja_env.get_template('hello_form.html')
return template.render()
或者您只返回HTML模板
or you just return the HTML templates
def home():
return render_template('home.html', posts=posts)
如果是的话,两者之间有区别吗?
is there a difference between the two if yes, what is it?
推荐答案
它们实际上是同一件事,您可能应该使用第二个,因为它更像是"Flask-y",并且可能会广播有关模板渲染的事件(尽管,机会是,您实际上并不关心那些事件.
They're effectively the same thing and you should probably use the second one because it's more "Flask-y" and may broadcast events about template rendering (although, chances are, you don't actually care about those events).
在Flask中, render_template
定义为:
In 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)
第一个参数是 代码的抽象版本> jinja_env.get_template
.同样, context
是可从模板访问的命名变量.最后,定义了 _render
就在上方,为:
The first argument is a slightly more abstract version of jinja_env.get_template
. Similarly, context
are the named variables that are accessible from the template. Finally, _render
is defined right above as:
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()
完全相同.
The first and third lines are broadcasting events that a template is getting rendered. If you have any Flask extensions, they may be listening for those events and doing extra things. Finally, the middle line is the exact same template.render()
you were calling yourself.
这篇关于在flask中返回render_templates和jinja templtes之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!