flask第二十三篇——模板【5】过滤器

请关注微信公众号:自动化测试实战

过滤器——format格式化

flaskDemo.py

# coding: utf-8

from flask import Flask, render_template
import flask

app = Flask(__name__)  # type: Flask
app.debug = True

@app.route('/')
def login():
    context = {
        "user": {
            "name": "Warren",
            "age": 18,
            "gender": None,
            "comment": u'<script>alert("弹出框")</script>'}
    }    
    return render_template('index.html', **context)

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

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>过滤器</title>
</head>
<body>
    <p>绝对值:{{ user.age | abs }}</p>
    <p>默认值:{{ user.gender or 'male'}}</p>
    <p>转义:{{ user.comment }}</p>
    <p>格式化:{{ "姓名:%s,年龄:%s" | format(user.name, user.age) }}</p>
</body>
</html>

 

我们在html文件中通过format引用姓名和年龄的值,传到模板里,执行代码:

过滤器——last和first(最后一个值和第一个值)

修改context的内容如下:

context = {
    "user": {
        "name": "Warren",
        "age": 18,
        "gender": None,
        "comment": u'<script>alert("弹出框")</script>'},
    "subject": ["math", "Chinese", "biology"]
}

index.html文件增加:

<p>最后一个值:{{ subject | last }}</p>
<p>第一个值:{{ subject | first }}</p>

保存后刷新页面:

还有很多过滤器,下面船长把有必要知道的给大家列在下面的代码里,大家可以去试一下:

flaskDemo.py

# coding: utf-8

from flask import Flask, render_template
import flask

app = Flask(__name__)  # type: Flask
app.debug = True

@app.route('/')
def login():
    context = {
        "user": {
            "name": "Warren",
            "age": 18,
            "gender": None,
            "comment": u'<script>alert("弹出框")</script>'},
        "subject": ["math", "Chinese", "biology"],
        "num": '3',
        "upper": "I AM A MAN",
        "lower": "i am a boy",
        "repl": "A, A, A",
        "title": u'life is short, I choose Python',
        "space": " abc ",
        "tags": u"<p>这是一个HTML标签</p>"}
    return render_template('index.html', **context)

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

 



index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>过滤器</title>
</head>
<body>
    <p>绝对值:{{ user.age | abs }}</p>
    <p>默认值:{{ user.gender or 'male'}}</p>
    <p>转义:{{ user.comment }}</p>
    <p>格式化:{{ "姓名:%s,年龄:%s" | format(user.name, user.age) }}</p>
    <p>最后一个值:{{ subject | last }}</p>
    <p>第一个值:{{ subject | first }}</p>
    <p>序列的长度:{{ subject | length }}</p>
    <p>拼接:{{ subject | join(', ') }}</p>
    <p>转换成整型:{{ num | int }}</p>
    <p>转换成小写:{{ upper | lower }}</p>
    <p>转换成小写:{{ lower | upper }}</p>
    <p>相同的全部替换:{{ repl | replace('A', 'HERO') }}</p>
    <p>只替换一个:{{ repl | replace('A', 'HERO', 1) }}</p>
    <p>截取字符串:{{ title | truncate(9) }}</p>
    <p>截断单词:{{ title | truncate(9, true) }}</p>
    <p>截取前后空格:{{ space | trim }}</p>
    <p>删除所有HTML标签:{{ tags | striptags }}</p>
</body>
</html>

 



执行代码:

 

posted @ 2018-04-07 10:25  孟船长  阅读(268)  评论(0编辑  收藏  举报