• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

Yancy00

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

flask-自定义过滤器

自定义中文日期过滤器
  1. 在单独文件comm.py中定义过滤器函数
    # 定义中文日期,时间过滤器处理函数
    def chinese_date_format(value,format='%Y年%m月%d日'):
    	return value.strftime(format)
    
    def chinese_time_format(value,format='%H时:%M分:%S秒'):
    	return value.strftime(format)
    

  2. 在flask入口文件app.py中绑定
    app.add_template_filter(chinese_date_format, 'cndate')
    app.add_template_filter(chinese_time_format, 'cntime')
    

  3. 在视图函数中传时间,日期参数给html页面
    @app.route('/filter2')
    def filter_demo2():
    	parameters = {
    		'date': datetime.datetime.today(),
    		'time': datetime.datetime.now()
    	}
    	return render_template('ffilter_demo2.html', **parameters)
    

  4. 在html模板页面中使用自定义过滤器cndate,cntime
    <body>
      <div>当前日期为: {{ date|cndate }}</div>
      <div>当前时间为: {{ time|cntime }}</div>
    </body>
    

  5. 显示结果
    image

posted on 2023-03-17 09:54  Yancy00  阅读(90)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3