Flask-Jinja2 template filter

Jinja2 template filter

The filter is used by the pipe symbol (|), for example: {{name | length}}, will return the length of name. The filter is equivalent to a function that passes the current variable into the filter, and then the filter returns the corresponding value according to its own function, and then renders the result to the page. There are many filters built into Jinja2, here you can see all the filters
• abs (value): returns the absolute value of a numeric value.
• default (value, default_value, boolean = false): If the current variable has no value, the value in the parameter will be used instead. name | default ('juran')-If name does not exist, juran will be used instead. boolean = False defaults to using the value in default only when this variable is undefined. If you want to use python to determine whether it is false, you can pass boolean = true You can also use or to replace.
• escape (value) or e: escape characters, which will escape symbols such as <,> into symbols in HTML. For example: content | escape or content | e.
• first (value): returns the first element of a sequence. names | first.
• format (value, * arags, ** kwargs): format string. For example, the following code:
last (value): returns the last element of a sequence. Example: names | last.
length (value): Returns the length of a sequence or dictionary. Example: names | length.
join (value, d = u ''): splice a sequence into a string with the value of the d parameter.
safe (value): If global escaping is turned on, the safe filter will turn off escaping of variables. Example: content_html | safe.
int (value): Convert the value to int type.
float (value): Converts the value to float type.
lower (value): Convert the string to lower case.
upper (value): Convert the string to lower case.
replace (value, old, new): Replace the string that replaces old with new.
truncate (value, length = 255, killwords = False): intercept the length length character string.
striptags (value): Remove all HTML tags in the string. If there are multiple spaces, they will be replaced with one space.
trim: Intercept blank characters before and after the string.
string (value): Convert the variable into a string.
wordcount (s): Count the number of words in a long string.

Flask template built-in filter:

# @ Time : 2020/4/11 15:48
# @ Author : Ellen

from flask import Flask,render_template
from datetime import datetime

app = Flask(__name__)
# 模版文件自动更新
app.config['TEMPLATES_AUTO_RELOAD'] = True


@app.route("/")
def index():
    context = {
        "username": "hello Ellen",
        "age": -18,
        "es": "<script>alert('hello');</script>",
        "h1": "<h1>hello</h1>",
        "books": ["Python","Java","PHP"],
        "address": "上海市闵行区"

    }
    return render_template("index.html",**context)

# 自定义模版过虑器
@app.template_filter("my_cut")
def cut(value):
    return value.replace("hello","")

自定义模版过虑器
@app.template_filter("handle_time")
def handle_time(time):
    """
    小于1分种:显示刚刚
    大于1分种小于1小时:显示多少分钟之前
    大于1小时小于24小时:显示xx小时之前
    :param time:
    :return:
    """
    if isinstance(time, datetime):
        now = datetime.now()
        # total_seconds 得到总秒数
        timestamp = (now - time).total_seconds()
        if timestamp < 60:
            return "刚刚"
        elif timestamp >=60 and timestamp <= 60*60:
            return "%s分钟之前" % int(timestamp/60)
        elif timestamp >= 60*60 and timestamp <= 60*60*24:
            return "%s小时之前" % int(timestamp/(60*60))
    else:
        return time


if __name__ == '__main__':
    app.run(debug=True)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>这是首页</h1>
    <p>{{ username }}</p>
    <p>{{ age|abs }}</p>
    <p>{{ name|default("这个人很懒,没有留下任何签名") }}</p>
    <!--自动转义-->
    {% autoescape off %}
    <p>{{ es }}</p>
    {% endautoescape %}
    <!--标记这个字符是安全的-->
    <p>{{es|safe}}</p>
    <p>{{h1|safe}}</p>
    <P>{{books|first}}</P>
    <P>{{books|last}}</P>
    <P>{{books|length}}</P>
    <P>{{books|first|length}}</P>
    <p>{{ username|upper }}</p>
    <p>{{ username|replace("hello","Hello") }}</p>
    <!-- 不会报错 但是没有显示 只有语法层面报错 才会显示   -->
    <p>{{ abc|replace("hello","Hello") }}</p>
    <!--  文章标题经常用到 -->
    <p>{{ username|truncate(length=5) }}</p>
    <p>{{ es|striptags() }}</p>
    <p>{{ username|trim }}</p>
    <p>{{ address|wordcount }}</p>
    <p>{{ username|my_cut }}</p>
	<p>文章发表时间:{{ now_time|handle_time}}</p>
</body>
</html>

Insert picture description here

Published 118 original articles · won praise 0 · Views 2664

Guess you like

Origin blog.csdn.net/weixin_45905671/article/details/105453606