API — Jinja2 2.7 documentation
macro.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% macro inputModel(name=name,value='',type='text',tips='') -%}
<input type="{{type}}" name = "{{name}}" value="{{value}}" placeholder="{{tips}}">
{%- endmacro %}
<div>{{ inputModel(name="username") }}</div>
<div>{{ inputModel(name="password",type="password") }}</div>
</body>
</html>
index.html
{% from 'macro.html' import inputModel %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<!--<input type="text" placeholder="请输入你的名字">-->
<h1>replace:{{name|replace('i','g')}}</h1>
<h1>{{age}}</h1>
<h1>abs:{{height|abs}}</h1>
<h1>大写:{{love.food|upper}}</h1>
<div>模板:{{inputModel(name='email',tips='请输入邮箱')}}</div>
<div>发布时间:{{now_time|push_time}}</div>
</body>
</html>
from flask import Flask,render_template
from datetime import datetime
app = Flask(__name__)
@app.route('/')
def hello_python():
data = {
'name':'Qianshui',
'age':'18',
'height':-170,
'love':{
'food':'potato'
},
'now_time':datetime(2024,8,12,23,30),
'it':['PYTHON','JAVA','PHP']
}
return render_template('index.html',**data)
@app.route('/macro/')
def show_macro():
return render_template('macro.html')
@app.template_filter('push_time')
def push_time(time):
"""
将 datetime 对象转换为相对时间或格式化时间字符串。
Args:
time (datetime.datetime): 需要转换的时间。
Returns:
str: 转换后的时间字符串。
"""
if isinstance(time,datetime):
cur_time = datetime.now()
subVal = (cur_time - time).total_seconds()
if subVal <= 60:
return '刚刚'
elif 60 < subVal <= 60*60:
return '1小时前'
elif 60*60 < subVal <= 60*60*24:
return '1天前'
else:
return time.strftime('%Y-%m-%d %H:%M:%S')
else:
return time
if __name__ == '__main__':
app.run(debug=True)