Fork me on GitHub

Flask 的 template模板 与 jinja2语法

Flask 的 template模板 与 jinja2语法

Flask使用的是Jinja2模板,所以其语法和Django基本无差别


>## 1、模板基本数据的渲染

变量 {{..}}
列表 {% for item in List %}

  • {{item}}
  • {% endfor %}
    字典 {% for k,v in Dict.items() %}
  • {{k}}{{v}}
  • {% endfor %}


    >## 2 注意:Markup等价django的mark_safe 用于返回有效的html标签

    也可以像django一样使用 {{data|safe}}


    >## 3 像django的simple_tag, filter 一样,传递自定义的函数

    局部函数 -- 只能在传入的template中使用,直接定义,传递

    def add_num(a,b):
    return int(a) + int(b)

    返回时:
    return render_template('..html','add_num':add_num)

    使用:

    全局 -- 全局使用

    django 的 filter可以当做if条件

    需要 @app.template_global()装饰器
    def func(a,b,c) --->> 全局temlate使用 {{func(a,b,c)}}

    和 @app.template_filter()装饰器
    def func(a,b,c) --->> 全局temlate使用 {{a|filter(b,c)}} # 需要管道符


    >## 4 模板继承

    {% extends 'layout.html' %}
    {% block body %}

    {% include 'asd.html' %}


    >## 5 定义宏: 相当于定义函数来控制html的内容

    一般是用于多次会用到的地方,比如分页

    在需要重用的html中写,paginator.html:

    {% macro page(data,url) -%}

    {% if data %}

    {%- endmacro %}

    调用:

    {% import 'admin/paginator.html' as pg %}


    例子:

    视图中:

    from flask import Flask,redirect,Markup,render_template,make_response
    app = Flask(name)

    全局使用

    @app.template_filter()
    def Filter(a,b,c):
    return min(a,b,c)

    全局使用

    @app.template_global()
    def Global(a,b,c):
    return a + b + c

    自定义函数 -- 局部

    def add_num(a,b):
    return int(a) + int(b)

    @app.route('/index',endpoint='index',methods=['GET'])
    def index():

    Dict = {
    'List':[1,2,3],
    'Dict':{'amy':18,'bob':20},
    'Str':'hello',
    'add_num':add_num,
    'tag':Markup('点击') # 或者在templates中使用 |safe
    }

    response = make_response(render_template('index.html',**Dict))
    return response

    if name == 'main':
    app.run()

    html中:

    hello!

    字符串:{{Str}}


      列表:
      {% for item in List %}

    • {{item}}

    • {% endfor %}
      字典:
      {% for k,v in Dict.items() %}

    • {{k}}{{v}}

    • {% endfor %}

    自定义加法函数:{{add_num(1,4)}}


    全局函数global:{{Global(1,4,5)}}


    全局函数filter:{{1|Filter(1,4)}}

    html标签:{{tag}}

    输出结果

    posted @ 2018-03-10 18:33  派对动物  阅读(4739)  评论(0)    收藏  举报
    Top