Flask 框架

render_templates
渲染模板
* 模板放在 templates 文件夹下
* 从 flask 中导入 render_templates 函数
* 在视图函数中,使用render_templates,只须要写模板 名称.html ,不须要写路径
除非是在templates下在建立子目录就须要把路径补充,以templates为根目录
@app.route('/')
def hello_world():
    return render_template('index.html')

 

 

 参数传递html

 

* 若是只有一个或者少许参数,直接在 render_templates 函数中添加关键字参数便可。
* 若是有多个参数,能够把全部的参数放在字典中,而后在 render_templates中使用“ **字典名 ” 转成关键参数传递进去。
* 在HTML模板中,若是使用一个变量让后台传参,HTML的语法是 “ {{params}}”
* 在HTML模板中的访问后台的属性或者字典,能够经过 {{params.property}}的形式,或者{{params['property']}}web

 

@app.route('/')
def index():
    class Person(object):
        name = u'姚明'
        age = 22

    p = Person()

    content = {
        'username': u'霸气的男人名字',
        'gender': u'男',
        'age': '20左右',
        'person': p,
        'websites': {
            'baidu': 'www.baidu.com',
            'taobao': 'www.taobao.com'
        }
    }
    return render_template('index.html', **content)

 

 

 

<body>
    这里就是HTML传来的!!
    <p>用户名: {{ username }}</p>
    <p>性别:{{ gender }}</p>
    <p>年龄:{{ age }}</p>

    <hr>
    <p>名字: {{ person.name }}</p>
    <p>年龄: {{ person.age }}</p>

    <hr>
    <p>百度: {{ websites['baidu'] }}</p>
    <p>淘宝: {{ websites['taobao'] }}</p>
</body>
相关文章
相关标签/搜索