Jinja2's template filter reference and customization

One, jinja2 template filter

  • The filter is used through the pipe symbol (|), for example: { {name|length }}, the length of name will be returned. 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 in Jinja2, you can see all the filters here

1. abs(value): Returns the absolute value of a numerical value.

2. 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. The default of boolean=False is to use the value in default only when the 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.

3. escape (value) or e: escape character, which will escape symbols such as <,> into symbols in HTML.

Examples: content|escape or content|e.

4. first(value): Returns the first element of a sequence.

Example: names|first.

5. format(value,*arags,**kwargs): format string.

For example, the following code: { {"%s"-"%s"|format('Hello?',"Foo!") }} will output: Helloo?-Foo!

6. last(value): Returns the last element of a sequence.

Example: names|last.

7. length(value): Returns the length of a sequence or dictionary.

Example: names|length.

8. join(value,d=u''): concatenate a sequence into a string with the value of the parameter d.

9. safe(value): If global escaping is turned on, the safe filter will turn off the escaping of the variable.

Example: content_html|safe.

10. int(value): Convert the value to int type.

11. Float(value): Convert the value to float type.

12. lower(value): Convert the string to lowercase.

13. upper(value): Convert the string to lowercase.

14. replace(value,old,new): Replace the string that replaces old with new.

15. truncate(value,length=255,killwords=False): intercept a string of length length.

16. striptags(value): Delete all HTML tags in the string. If multiple spaces appear, they will be replaced with one space.

17. trim: Intercept the blank characters before and after the string.

18. string(value): Convert a variable to a string.

19. wordcount(s): Count the number of words in a long string.

Two, custom filter

1. Filter definition:

@app.template_filter("filter name")
def
The function implemented by the filter name (parameter)

2.The reference of the filter:

  • The same as the system filter reference method,
    • { {Variable name|filter name}}
    • { {Variable name|filter name (parameter)}}

Three, examples

1. Code:

from flask import Flask,render_template
from datetime import datetime

app=Flask(__name__)

@app.route('/')
def index():
    context = {
    
    
        'username': 'hello 老萝卜',
        'age': -18,
        'home': '湖北',
        'recommend': 'chinapost',    # 删除后,应显示缺省值
        'es': "<script>alert('hello    everyone');</script>",
        'books': ['Python', 'Java', 'PHP'],
        'book': {
    
    'Python': 666},
        'address': '中国   湖北省   武汉市      东西湖区',
        'now_time': datetime(2020, 10, 14, 21, 7, 0)
    }
    return render_template('demo_jinja2filter.html', **context)   # 引用模板

# 自定义过滤器
@app.template_filter('my_filter')
def my_filter(value):
    return value.replace('hello', '')

@app.template_filter('handler_time')
def handler_time(time):
    """
    小于一分钟---->刚刚
    大于一分钟小于一小时---->xxx分钟之前
    大于一小时小于24小时----> xxx小时之前
    """
    now = datetime.now()
    # 获取总秒数
    timestamp = (now - time).total_seconds()

    if isinstance(time, datetime):
        if timestamp < 60:
            return '刚刚'
        elif 60 <= timestamp <= 60*60:
            return '%s分钟之前' % int(timestamp/60)
        elif 60*60 < timestamp <= 60*60*24:
            return '%s小时之前' % int(timestamp/(60*60))
    else:
        return time


if __name__=="__main__":
    app.run(debug=True)

2. Template

Templates are generally placed in the ./templates directory, it is recommended not to change the directory casually

#./templates/demo_jinja2filter.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Jinja2过滤器演示</title>
</head>
<body>
    <h1>首页</h1>
    用户姓名:{
    
    {
    
     username }}
    <p>年龄: {
    
    {
    
     age|abs }} (原值:{
    
    {
    
    age}}</p>
    <p>{
    
    {
    
     name|default('这个人很懒,什么都没有留下') }}</p>
    {
    
    % autoescape off %}
     <p>{
    
    {
    
     es }}</p>
    {
    
    % endautoescape %}
    <p>{
    
    {
    
     es|safe }}</p>
    <p>返回一个序列{
    
    {
    
    books}}的第一个元素:{
    
    {
    
     books|first }}</p>
    <p>返回一个序列{
    
    {
    
    books}}的最后一个元素:{
    
    {
    
     books|last }}</p>
    <p>返回一个序列{
    
    {
    
    books}}的长度:{
    
    {
    
     books|length }}</p>
    <p>返回一个字典{
    
    {
    
    book}}的长度:{
    
    {
    
     book|length }}</p>
    <p>返回一个序列{
    
    {
    
    books}}的第一个元素长度:{
    
    {
    
     books|first|length }}</p>
    <p>字符串{
    
    {
    
    username}}替换"replace('萝卜', 'luobo')"{
    
    {
    
     username|replace('萝卜', 'luobo') }}</p>
    <p>字符串{
    
    {
    
    username}}截取:{
    
    {
    
     username|truncate(length=5) }}</p>
    <p>删除字符串"{
    
    {es}}"中所有的HTML标签,如果出现多个空格,将替换成一个空格:{
    
    {
    
     es|striptags }}</p>
    <p>计算一个长字符串"{
    
    {address}}"中单词的个数:{
    
    {
    
     address|wordcount }}</p>
    <p>{
    
    {
    
     username|my_filter }}</p>
    <p>博客发表时间:{
    
    {
    
     now_time|handler_time }}</p>
</body>
</html>

Insert picture description here

Guess you like

Origin blog.csdn.net/laoluobo76/article/details/109095318