首页 > 技术文章 > 9_flask中的模板渲染和模板传参及其技巧

chengshifei 2019-10-07 18:51 原文

模板传参

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

  1. 后台传参
@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)
  1. 前台获取参数
<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 }}

推荐阅读