如何在Jinja中制作“封装”碎片

2024-10-01 17:25:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个小小的Flask+Jinja应用程序,它需要有一个带有用户部分的通用标题(见下文)

enter image description here

现在,这个部分必须出现在任何页面上,并且因为它必须包含用户名,我想知道是否有任何方法可以避免为每个呈现的页面传递用户详细信息(请参见uservariable bellow)

...
return render_template('home.html', user=userDetails, entries=entriesList, bla=blaValue)    

我知道PHP和JSP允许您创建具有自己本地逻辑的“封装”片段,但我想知道Jinja(和Flask)是否也可以实现同样的功能


Tags: 方法用户应用程序标题flaskreturn详细信息template
1条回答
网友
1楼 · 发布于 2024-10-01 17:25:09

使用template inheritance在所有页面上显示用户部分。你将有:

  • 基本模板(包含当前用户部分的框架和用于以下内容的空间)
  • 子模板(在右上角显示用户部分的每个页面

然后在flask中,您需要为每个模板传递user=userDetails

from flask_login import current_user

def render_template_with_user(*args, **kwargs):
    """renders the template passing the current user info"""
    return render_template(*args, user=current_user, **kwargs)

您还可以使用include statement在父模板中的某个位置导入模板

{% include 'header.html' %}
    Body
{% include 'footer.html' %}

您可以将它与with statement组合起来,将一些变量传递给包含的组件

{% with username = user.name %} {% include 'header.html' %} {% endwith %}
    Body
{% include 'footer.html' %}

相关问题 更多 >

    热门问题