[TOC]
# 五、flask模板渲染
py文件:
```python
from flask import Flask,render_template,Markup
app = Flask(__name__)
app.debug = True
USERS = {
1:{'name':'张三','age':18,'gender':'男','text':"道路千万条"},
2:{'name':'李四','age':28,'gender':'男','text':"安全第一条"},
3:{'name':'王五','age':18,'gender':'女','text':"行车不规范"},
}
def func1(arg,tank):
return Markup(f"
饼哥正帅,{arg} is sb {tank} is same as {arg}
")
@app.route("/")
def index():
# data = {
# "user" :USERS,
# "name": "jason"
# }
return render_template("index.html",user = USERS,name="jason",ht1 = func1,ht="
饼哥正帅
")
#return render_template("index.html",**data)
if __name__ == '__main__':
app.run()
```
## 5.1 变量的循环
```html
Title
我是html
{% for k,v in user.items() %}
{{ k }} |
{{ v.name }} |
{{ v['name'] }} |
{{ v.get('name') }} |
{{url_for("index")}} |
{% endfor %}
```
## 5.2 逻辑判断
```html
Title
用户列表
{% if name %}
Hello {{ name }}!
{% else %}
Hello World!
{% endif %}
```
## 5.3 执行函数,传参数
**比django中多可以加括号,执行函数,传参数**
```python
from flask import Flask,render_template,Markup
app = Flask(__name__)
app.debug = True
def func1(arg,tank):
return Markup(f"饼哥正帅,{arg} is sb {tank} is same as {arg}
")
@app.route("/")
def index():
# data = {
# "user" :USERS,
# "name": "jason"
# }
return render_template("index.html",ht1 = func1,ht="饼哥正帅
")
if __name__ == '__main__':
app.run()
```
html文件
```html
Title
{{ ht|safe}}
{{ht1("jaosn","tank")}} // 传参数
```
加载全部内容