模版的语法:
1、在模版中获取view中传递的变量值: {{ 变量名key }}
render_template('模版名字',key=value,key=value)
可以传递的类型有很多常见的如下几种:
字符串:name = 'geyanan'
整型: age = 19
list:friends = ["zhouqiang","mike","nike"]
dict: dict1 = {"name":"zhouqiang","age":30,"sex":"man"}
自定义构建的类型:Girl("yanan","beijing")
模版:
{{ list.0 }} 同 {{ list[0] }}
{{ dict.key }} 同 {{ dict.get(key) }}
{{ girl.name }} 同 {{ 对象.属性 }}
案例:app.py
from flask import Flask from flask import make_response, request, render_template,redirect,url_for import setting,json app = Flask(__name__) app.config.from_object(setting) class Girl: def __init__(self,name,addr): self.name = name self.addr = addr self.gender = '女' def __str__(self): return self.name @app.route('/show') def show(): name = 'geyanan' age = 19 friends = ["zhouqiang","mike","nike"] dict1 = {"name":"zhouqiang","age":30,"sex":"man"} girlfriend = Girl("yanan","beijing") return render_template('test.html',name = name,age = age,friends = friends,dict1 = dict1,girl = girlfriend) # 如果没有找到匹配的,会以空白字符串填充 # 如果没有找到匹配的,会以空白字符串填充 if __name__ == '__main__': app.run(host='127.0.0.1', port=5000)
页面断获取数据方法:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <div>用户信息展示</div> <p> 用户名信息:{{ name }} -- {{ age }} -- {{ sex }} <br> {{ friends.0 }} {{ friends[0] }} <br> {{ dict1.get(name) }} {{ dict1.name }} <br> {{ girl.name }} {{ girl.addr }} {{ girl.gender }} </p> </body> </html>