Skip to main content
 首页 » 编程设计

python之flask 中返回 render_template 和 jinja 模板的区别

2024年09月07日8tuyile006

我见过两种在 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) 

两者有区别吗,如果有,是什么?

请您参考如下方法:

它们实际上是同一件事,您可能应该使用第二个,因为它更像“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() 完全相同。