Flask快速入门(5) — 模板渲染
Flask快速入门(5) — 模板渲染
视图函数
from flask import Flask,request,render_template,Markup
app = Flask(__name__)
@app.route('/',endpoint='index')
def index():
age = 18
classes = '班级'
schools = ['s1','s2','s3']
USER = {
1: {'name': 'Nick', 'age': 18, 'hobby': ['study', 'swimming']},
2: {'name': 'Bob', 'age': 19, 'hobby': ['basketball', 'game']},
3: {'name': 'Link', 'age': 17, 'hobby': ['sing', 'dance']},
4: {'name': 'Sean', 'age': 20, 'hobby': ['game', 'walking']},
}
safe_test = '<h1>测试xss</h1>'
return render_template('index.html',info=USER,classes=classes,schools=schools,age=age,safe_test=safe_test)
@app.route('/login')
def login():
return Markup('<h1>我最帅</h1>') #
if __name__ == '__main__':
app.run()
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--字符串渲染-->
<p>
classes: {{ classes }}
</p>
<!--列表取值-->
{{schools.0}}
{{schools[1]}}
{{schools[:-1]}}
<!--列表循环-->
<ul>
{% for school in schools %}
<li>{{ school }}</li>
{% endfor%}
</ul>
<!--字典循环-->
{% for key,val in info.items() %}
{{ val.name}}
{{ val['name']}}
{{ val.get('name')}}
{% endfor %}
<!--逻辑判断-->
{% if age > 10 %}
<h1>{{age}}</h1>
{% endif %}
无safe时,不解析标签 {{safe_test}}
<br>
有safe时,解析标签{{safe_test|safe}}
</body>
</html>
与django不同的是,在flask中模板渲染可以用[],()之类的,执行函数,传参数。
from flask import Flask,render_template,Markup,jsonify,make_response
app = Flask(__name__)
def func1(arg):
return Markup("<input type='text' value='%s' />" %(arg,))
@app.route('/')
def index():
return render_template('index.html',ff = func1) # 传了函数过去
if __name__ == '__main__':
app.run()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--执行函数-->
{{ff('六五')}}
{{ff('六五')|safe}}
</body>
</html>
注意:
1.Markup等价django的mark_safe
2.用于模板的extends,include与django中的一模一样