[Jinjia2] 模板渲染,模板访问对象属性,过滤器属性,控制语句,
项目目录结构:
Flask-learning
static
templates
blog_detail.html
control.html
filter.html
index.html
app.py
app.py
------------------------------------------------------------------
from flask import Flask , request ,render_template
from datetime import datetime
app = Flask(__name__)
# 自定义过滤器
def data_format(value,format = "%Y-%d-%m "):
return value.strftime(format)
app.add_template_filter(data_format,"dformat")
class User:
def __init__(self,username,email):
self.username = username
self.email = email
@app.route('/')
def hello_world():
user = User(username="li", email= "123@qq.com")
person = {
"name" :"zhangsan",
"password" : "123"
}
return render_template("index.html" , user = user , person = person)
@app.route("/blog/<id>")
def blog_detail(id):
return render_template("blog_detail.html",blog_id = id)
@app.route("/fiter")
def filter():
user = User(username="li", email= "123@qq.com")
mytime = datetime.now()
books = [{
"name" : " sanguo",
"author" : "luoguanzhong"
},{
"name": " shuihu",
"author": "shinaian"
},]
return render_template("fiter.html" , user =user,mytime = mytime,books =books )
@app.route("/control")
def control():
age = 17
books = [{
"name": " sanguo",
"author": "luoguanzhong"
}, {
"name": " shuihu",
"author": "shinaian"
}, ]
return render_template("control.html" ,age = age ,books =books )
if __name__ == '__main__':
app.run(debug=True)
------------------------------------------------------------
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
</head>
<body>
This is Main page!
{{user.username}}
{{user.email}}
{{person.name}}
</body>
</html>
---------------------------------------------------------------
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>过滤器</title>
</head>
<body>
{{user.username}} - {{user.username | length }}
<div> {{ mytime | dformat}} </div>
</body>
</html>
--------------------------------------------------------------------------
comtrol.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>控制语句</title>
</head>
<body>
{% if age > 18 %}
<div> 已经成年</div>
{% elif age < 18 %}
<div> 未成年</div>
{% else %}
<div> 成年</div>
{% endif %}
{% for book in books %}
<div>{{book.name}} , {{ book.author }}</div>
{% endfor %}
</body>
</html>
网友评论