Python Web開發之Flask框架(二)
阿新 • • 發佈:2020-08-20
jinjia2模板渲染引擎
我們訪問的頁面需要在使用者訪問時根據程式邏輯動態生成,模板就是包含變數和運算邏輯的HTML或其他格式的文字,執行這些變數替換和邏輯計算工作的過程叫做渲染;
按照預設,Flask會從程式例項所在同級目錄的templates資料夾中尋找模板(建立的模板可以存放在新建的templates資料夾中)
模板基本語法
三種常用定界符:
- {{ … }} 用來標記變數。
- {% … %} 用來標記語句,比如if語句,for語句等。
- {# … #} 用來寫註釋。
模板中使用的變數需要在渲染的時候傳遞進去。
在templates目錄下建立一個index.html檔案作為模板。
index.html模板
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>{{ name }}'s Watchlist</title> </head> <body> <h2>{{ name }}'s Watchlist</h2> {# 使用 length 過濾器獲取 movies 變數的長度 #}
<p>{{ movies|length }} Titles</p> <ul>
{% for movie in movies %} {# 迭代 movies 變數 #} <li>{{ movie.title }} - {{ movie.year }}</li> {# 等同於 movie['title'] #} {% endfor %} {# 使用 endfor 標籤結束 for 語句 #}
</ul> <footer> <small>© 2018 <a href="http://helloflask.com/tutori al">HelloFlask</a></small> </footer> </body> </html>
為模板準備一些虛擬資料:
name = 'fuyuan' movies = [{'title':'流浪地球','year':'2019'}, {'title':'哥斯拉2','year':'2019'}, {'title':'唐人街探案2','year':'2020'}, {'title':'復仇者聯盟2','year':'2020'}, {'title':'影子特工隊','year':'2019'}, {'title':'星球大戰3','year':'2018'}]
通過使用render_template( )函式可以把模板渲染出來,傳入的引數為模板的檔名,即上面的’index.html’,還有模板中需要傳入的引數;
#--coding:utf-8 -- from flask import Flask,render_template app = Flask(__name__) name = 'fuyuan' movies = [{'title':'流浪地球','year':'2019'}, {'title':'哥斯拉2','year':'2019'}, {'title':'唐人街探案2','year':'2020'}, {'title':'復仇者聯盟2','year':'2020'}, {'title':'影子特工隊','year':'2019'}, {'title':'星球大戰3','year':'2018'}] @app.route('/index') def index(): return render_template('index.html',name = name,movies = movies) if __name__ == '__main__': app.run(host='0.0.0.0',debug= True)
在render_template函式中左邊的name/movies是index.html模板中使用的變數名,右邊的name/movies是該變數實際指向的物件,這裡模板中name變數實際指向的是虛擬資料中name字串,模板中movies變數實際指向的是虛擬資料中movies列表,當然模板中傳入的資料結構也可包含,元祖、字典、函式等。
執行上述程式碼,在瀏覽器中輸入http://localhost:5000/index,瀏覽器返回如下主頁。