flask学习(十三):过滤器

1. 介绍和语法

介绍:过滤器可以处理变量,把原始的变量经过处理后再展示出来,作用的对象是变量

语法:

{{ avatar|default('xxx') }}

2. default过滤器:如果当前变量不存在,这时候可以指定默认值

实例1:

建立一个filter_demo.py文件

#encoding=utf-8
from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html', avatar='https://avatar.csdn.net/B/8/F/1_weixin_38323645.jpg')


if __name__ == '__main__':
    app.run()
View Code

index.html内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <img src="{{ avatar|default('https://avatar.csdn.net/9/D/E/1_yh0vlde8vg8ep9vge.jpg') }}" alt="">
</body>
</html>
View Code

代码运行结果:

扫描二维码关注公众号,回复: 3386016 查看本文章

实例2:

去除filter_demo.py中的返回值

#encoding=utf-8
from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')


if __name__ == '__main__':
    app.run()
View Code

代码运行结果:

3. length过滤器:求出列表/字符串/字典/元组的长度

实例1:

filter_demo.py文件

#encoding=utf-8
from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def index():
    comments = [
        {
            'user': u'小翟',
            'content': 'xxxx'
        },
        {
            'user': u'flask知识',
            'content': 'xxxx'
        }
    ]
    return render_template('index.html', comments=comments)


if __name__ == '__main__':
    app.run()
View Code

index.html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <img src="{{ avatar|default('https://avatar.csdn.net/9/D/E/1_yh0vlde8vg8ep9vge.jpg') }}" alt="">

    <hr>

    <p>评论数:{{ comments|length }}</p>
    <ul>
        {% for comment in comments %}
            <li>
                <a href="#">{{ comment.user }}</a>
                <p>{{ comment.content }}</p>
            </li>
        {% endfor %}
    </ul>
</body>
</html>
View Code

代码运行结果:

猜你喜欢

转载自www.cnblogs.com/cnhkzyy/p/9716325.html