3 jinja2模板

 

 

video17 jinja2过滤器html

过滤器经过管道符号进行使用。如{{ name | length }}将返回name的长度,过滤器至关因而一个函数。python

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中同样,都为真则取第一个,都为假就取后一个。app

 

 

video20 自定义过滤器ide

如下为一个字符串替换的过滤器。函数

 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 }}

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

 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 条件判断3d

 video23 for循环code

 video25 宏htm

这部分请移步:http://www.javashuo.com/article/p-eulclzse-dn.htmlblog

相关文章
相关标签/搜索