Filter video17 jinja2
Filters used by the pipe symbol. The {{name | length}} returns the name length is equivalent to a filter function.
. 1 DEF the hello_world (): 2 Intro = '' will be displayed here # Default None empty or time. . 3 return the render_template ( ' index.html ' , = Intro Intro) . 4 . 5 {{Intro | default ( ' who is lazy, did not leave a message. ' , Boolean = True )}}
, or:
Intro {{ or 'this person was lazy, did not leave a message. '}}
Here or in python and like all true then take the first one, they are false just after taking a.
Custom filter video20
The following is a replaceable filter string.
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 宏