jinja2随笔

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)

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值