flask框架2(jinja2)

  • Jinja2:是 Python 下一個被普遍應用的模板引擎,是由Python實現的模板語言
  • Flask提供的 render_template 函數封裝了該模板引擎
  • render_template 函數的第一個參數是模板的文件名,後面的參數都是鍵值對,表示模板中變量對應的真實值
  • 使用時導入:from flask import Flask,render_template
    能夠直接做爲返回值return render_template('flask_jinja2_01.html')
  • 使用
    • 模板內使用{{}} 來表示變量名,這種 {{}} 語法叫作變量代碼塊 {{dict['key']}}
    • 用 {%%} 定義的控制代碼塊,好比循環或者if語句
      if/else if /else / endif
      for / endfor
    • 使用 {# #} 進行註釋
  • 過濾器
    • 過濾器的使用方式爲:變量名 | 過濾器
      {{variable | filter_name(*args)}}
    • 若是沒有任何參數傳給過濾器,則能夠把括號省略掉
    • 過濾器支持鏈式調用:{{ "hello world" | reverse | upper }}
  • 自定義過濾器
    • 經過Flask應用對象的 add_template_filter 方法:app.add_template_filter(方法函數名,‘自定義的過濾器名字’)
    • 經過裝飾器裝飾過濾器方法:@app.template_filter('自定義的過濾器名字')
  • if語句 過濾器能夠用在語句中
{%if xxx %}
        <a href='#'>xxx</a>
    {% else %}
        <a href='#'>xxx</a>
    {% endif %}
  • 循環
{% for item in items %}
        <div>
            <h1>{{xxxx }}</h1>
            <p>{{ xxxx }}</p>
       </div>
    {% endfor %}
  • 繼承
    • 父模板中寫入block
    {% block top %} {% endblock %}
    • 子模板獲取並重寫
    {% extends 'base.html' %}
              {% block top %}
               #須要填充的內容
              {% endblock content %}
相關文章
相關標籤/搜索