美文网首页
python-Flask(jinja2)传参

python-Flask(jinja2)传参

作者: SmallPot_Yang | 来源:发表于2018-03-30 11:01 被阅读0次

传参

[TOC]

较少的参数:直接在render_template函数中定义关键字参数。在模板中使用{{ var }}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <p>这是一个模板文件</p>
    <p>你好:{{ username }}</p>
</body>
</html>
@app.route('/')
def index():
 # 模板文件中只有一个变量,直接把参数传进去
    return render_template('index.html',username='你好')



多参数:使用字典,在render_template函数中用两个**将字典转换成关键字参数

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <p>这是一个模板文件</p>
    <p>用户名:{{ username }}</p>
    <p>年龄:{{ age }}</p>
    <p>性别:{{ gender }}</p>
</body>
</html>
@app.route('/')
def index():
    context = {
        'username' : '站长',
        'age' : '18',
        'gender' : '男'
    }
    return render_template('index.html' , **context)
    # 定义一个字典,双星号把字典转换成关键参数传递进去


访问模型类:使用访问字典的方式,{{ params.property }}或者{{ params['age'] }}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>index</title>
</head>
<body>
    <p>这是一个模板文件</p>
    <p>用户名:{{ username }}</p>
    <p>年龄:{{ age }}</p>
    <p>性别:{{ gender }}</p>

    <hr>
    <p>访问模型(类)</p>
    <p>用户名:{{ person['name'] }}</p>
    <p>年龄:{{ person.age }}</p>

    <hr>
    <p>访问字典</p>
    <p>百度:{{ websites.baidu }}</p>
    <p>谷歌:{{ websites.google }}</p>
</body>
</html>
@app.route('/')
def index():
    # 定义一个类
    class Person(object):
        name = '老头'
        age = 22

    p = Person() # 实例化对象

    context = {
        'username' : '站长',
        'age' : '18',
        'gender' : '男',
        'person' : p,  # 把模型对象作为参数传进去
        # 将一个字典嵌套传参数进去
        'websites' : {
            'baidu' : 'www.baidu.com',
            'google' : 'www.google.com'
            }
        }
# 定义一个字典,双星号把字典转换成关键参数传递进去
    return render_template('index.html' , **context) 

相关文章

网友评论

      本文标题:python-Flask(jinja2)传参

      本文链接:https://www.haomeiwen.com/subject/cvgbcftx.html