Flask 模板(一),flask模板
使用模板有助於將商務邏輯與表現邏輯分開,更易於維護。模板是已經建立的網頁代碼,其中部分動態資料需要在請求的上下文中用具體值替換。
flask中使用了Jinja2模板引擎,儲存在templates檔案夾中。
templates/index.html
<h1>Hello World!</h1>
使用 {{ name }} 佔位
templates/user.html<h1>Hello, {{ name }}!</h1>
模板的渲染
模板的渲染即用真實值取代模板中的佔位變數的過程。
from flask import Flask,render_template@app.route('/')def index(): return render_template('index.html',name=name)
變數可以從列表、字典和對象擷取。
<p>A value from a dict:{{ mydict['key'] }}</p><p>A value from a list:{{ mylist[3] }}</p><p>A value from a list with a variable index:{{ mylist[intvar] }}</p><p>A value from a object's method :{{ myobj.mymethod() }}</p>
使用過濾器修改變數:
{{ name|capitalize }}
常用過濾器:
| 過濾器名 |
說明 |
| safe |
渲染時不轉義 |
| capitalize |
首字母大寫,其他小寫 |
| lower |
小寫 |
| upper |
大寫 |
| title |
每個單字首大寫 |
| trim |
去掉首尾空格 |
| striptags |
把值中所有html標籤刪掉 |
控制結構
{% if user %} Hello,{{ user }}{% else %} Hello,Stranger!{% endif %}
<ul> {% for comment in comments %} <li>{{ comment }}</li> {% endfor %}</ul>