码迷,mamicode.com
首页 > 其他好文 > 详细

3 jinja2模板

时间:2019-08-18 17:37:39      阅读:110      评论:0      收藏:0      [点我收藏+]

标签:replace   amp   hand   second   条件   html   通过   class   ide   

 

技术图片

技术图片

 

video17 jinja2过滤器

过滤器通过管道符号进行使用。如{{ name | length }}将返回name的长度,过滤器相当于是一个函数。

技术图片

1 def hello_world():
2     intro = ‘‘  #这里为空或None时候会显示默认值。
3     return render_template(index.html,intro=intro)
4 
5 {{ intro | default(此人很懒,没留下信息。,boolean =True)}}
或者:
{{ intro or ‘此人很懒,没留下信息。‘ }}


技术图片

这里的or和python中一样,都为真则取第一个,都为假就取后一个。

技术图片

 技术图片

 

video20 自定义过滤器

以下为一个字符串替换的过滤器。

 1 @app.route(/)
 2 def hello_world():
 3     intro = hello,world!what are you...?
 4 
 5     return render_template(index.html,intro=intro)
 6 
 7 @app.template_filter(my_cut)
 8 def cut(value):
 9     value = str(value).replace(hello,Hi)
10     return value
11 
12 
13 {{ intro | my_cut }}

下面讲一个时间戳的过滤器。

 1 @app.route(/)
 2 def hello_world():
 3     intro = hello,world!what are you...?
 4     create_time = datetime(2019,8,15,12,32,15)  #设置任意时间
 5     return render_template(index.html,intro=intro,create_time=create_time)
 6 
 7 @app.template_filter(handle_time)  #设置过滤器名称
 8 def handle_time(time):
 9     if isinstance(time,datetime):
10         now = datetime.now()
11         timestamp = (now - time).total_seconds()  #换算为秒
12         if timestamp < 60:
13             return 刚刚
14         elif timestamp >= 60 and timestamp < 60* 60:
15             return "%s分钟前" %str(int(timestamp / 60))
16         elif timestamp >= 60 * 60 and timestamp < 60 * 60 * 24:
17             return "%s小时前" % str(int(timestamp / 60 / 60))
18         elif timestamp > 60 * 60 * 24:
19             return time.strftime(%Y/%m%d %H:%M)  #按照‘2019/0815 12:32’格式输出
20     else:
21         return time.strftime(%Y/%m%d %H:%M)
22 
23 
24 {{ create_time | handle_time }}

 

 

video22 条件判断

 video23 for循环

 video25 宏

这部分请移步:https://www.cnblogs.com/two-peanuts/p/11341367.html

3 jinja2模板

标签:replace   amp   hand   second   条件   html   通过   class   ide   

原文地址:https://www.cnblogs.com/two-peanuts/p/11363315.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!