问题
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()
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?
回答1:
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).
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)
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
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.
来源:https://stackoverflow.com/questions/50900830/difference-between-returning-render-templates-and-jinja-templtes-in-flask