Flask模板

1. Jinja2模板

6.1 基本流程

使用flask 中的render_template渲染模板

 

<!DOCTYPE html>

<html lang="en">

<head>

    <meta charset="UTF-8">

    <title>Template</title>

</head>

<body>

<h1>hello {{ name }}</h1>

    <h1>hello {{ age }}</h1>

<h1>my_dict: city= {{ my_dict[“city”] }}</h1>

<h1>my_dict: city= {{ my_dict.city }} </h1>

<h1>my_list: {{ my_list }} </h1>

<h1>my_list[my_int]: {{ my_dict[my_int] }} </h1>

<h1>my_list[0]+my_list[1]= {{ my_dict[0]+my_dict[1] }} </h1>

</body>

</html>
# 传字典需要加< **>

from flask import Flask,render_template,

@app.route("/index")

def index():

    data = {

        "name": "python",

        "age": 18,

        "my_dict": {"city": "sz"},

        "my_list": [1, 2, 3, 4, 5],

        "my_int": 0

    }

    return render_template("index.html", **data)

6.2 变量

<p>{{mydict['key']}}</p>

<p>{{mydict.key}}</p>

<p>{{mylist[1]}}</p>

<p>{{mylist[myvariable]}}</p>
from flask import Flask,render_template
app = Flask(__name__)

@app.route('/')
def index():
    mydict = {'key':'silence is gold'}
    mylist = ['Speech', 'is','silver']
    myintvar = 0

    return render_template('vars.html',
                           mydict=mydict,
                           mylist=mylist,
                           myintvar=myintvar
                           )
if __name__ == '__main__':
    app.run(debug=True)

6.3 过滤器

6.3.1 字符串过滤器

safe:禁用转义;

  <p>{{ '<em>hello</em>' | safe }}</p>

 

capitalize:把变量值的首字母转成大写,其余字母转小写;

  <p>{{ 'hello' | capitalize }}</p>

 

lower:把值转成小写;

  <p>{{ 'HELLO' | lower }}</p>

 

upper:把值转成大写;

  <p>{{ 'hello' | upper }}</p>

 

title:把值中的每个单词的首字母都转成大写;

  <p>{{ 'hello' | title }}</p>

 

trim:把值的首尾空格去掉;

  <p>{{ ' hello world ' | trim }}</p>

 

reverse:字符串反转;

  <p>{{ 'olleh' | reverse }}</p>

 

format:格式化输出;

  <p>{{ '%s is %d' | format('name',17) }}</p>

 

striptags:渲染之前把值中所有的HTML标签都删掉;

  <p>{{ '<em>hello</em>' | striptags }}</p>

 

6.3.2 支持链式使用过滤器

<p>{{ “ hello world  “ | trim | upper }}</p>

6.3.3 列表过滤器

first:取第一个元素  

  <p>{{ [1,2,3,4,5,6] | first }}</p>

 

last:取最后一个元素

  <p>{{ [1,2,3,4,5,6] | last }}</p>

 

length:获取列表长度

  <p>{{ [1,2,3,4,5,6] | length }}</p>

 

sum:列表求和

  <p>{{ [1,2,3,4,5,6] | sum }}</p>

 

sort:列表排序

  <p>{{ [6,2,3,1,5,4] | sort }}</p>

 

6.3.4 自定义过滤器

自定义的过滤器名称如果和内置的过滤器重名,会覆盖内置的过滤器。

 

方式一:

通过 add_template_filter (过滤器函数, 模板中使用的过滤器名字)

方式二:

通过装饰器  app.template_filter (模板中使用的装饰器名字)

定义后可以在前端使用

<h1>{{ my_list | double_2 }}</h1>

<h1>{{ my_list | db3 }}</h1>

 

posted @ 2018-11-20 12:58  wsg-python  阅读(111)  评论(0)    收藏  举报