你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

flask中的模板渲染和模板传参及其技巧

2021/12/30 12:15:07

flask中的模板渲染和模板传参及其技巧
前端有时需要传入数据为了方便我们写成一个方法

def ops_rander(templates,context={}):
    if "current_user" in g:
        context["current_user"] = g.current_user
    return render_template(templates,**context)

模板传参
在使用render_template 渲染模板的时候,可以传递关键字参数, 如果你的参数过多,那么可以将所有的参数放到一个字典中,然后 传这个字典参数的时,使用两个星号,将字典打散成关键字参数

后台传参
python

@app.route('/')
def index():
    # return render_template('index.html', name='long', age=18, country='china')

    context = {
        'name': 'long',
        'age': 18,
        'country': 'china'
    }
    return render_template('index.html', **context)

前台获取参数

<body>
    index
    <p>名字: {{ name }}</p>
    <p>年龄: {{ age }}</p>
    <p>国家: {{ country }}</p>
</body>

如果后台是下面这样子传

context = {
    'name': 'long',
    'age': 18,
    'country': 'china'
}
return render_template('index.html', context=context)

则前台应该这样子获取参数:

{{ context.name }}
{{ context.age }}
{{ context.country }}