Flask 框架
render_templates
渲染模板
* 模板放在 templates 文件夹下
* 从 flask 中导入 render_templates 函数
* 在视图函数中,使用render_templates,只需要写模板 名称.html ,不需要写路径
除非是在templates下在创建子目录就需要把路径补充,以templates为根目录
@app.route('/')
def hello_world():
return render_template('index.html')
参数传递
* 如果只有一个或者少量参数,直接在 render_templates 函数中添加关键字参数即可。
* 如果有多个参数,可以把所有的参数放在字典中,然后在 render_templates中使用“ **字典名 ” 转成关键参数传递进去。
* 在HTML模板中,如果使用一个变量让后台传参,HTML的语法是 “ {{params}}”
* 在HTML模板中的访问后台的属性或者字典,可以通过 {{params.property}}的形式,或者{{params['property']}}@app.route('/')
@app.route('/') def index(): class Person(object): name = u'李xx' 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)
index.html 文件,放在py同级的templates文件夹里面
<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>

浙公网安备 33010602011771号