[譯]Flask教程-模版

咱們能夠讓綁定到某個URL的函數返回HTML. 好比下面的代碼中, hello()函數會返回由<h1>包裹的Hello World字符串.html

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
   return '<html><body><h1>Hello World'</h1></body></html>'

if __name__ == '__main__':
   app.run(debug = True)

但你們看得出, 這樣直接經過python代碼返回HTML內容顯得很笨, 尤爲當咱們碰到須要對輸入變量作條件判斷和循環時, 咱們常常須要作字符串嵌入拼接這種體力活.
這種狀況下, 咱們須要利用Flask自帶的Jinja2模版引擎. 咱們能夠經過render_template()來渲染HTML文件, 而不是直接把HTML直接硬編碼在python代碼中. 好比:python

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
   return render_template(‘hello.html’)

if __name__ == '__main__':
   app.run(debug = True)

Flask會默認嘗試從腳本執行目錄下的templates文件夾中尋找HTML模版文件,web

--腳本目錄
 |_ Hello.py
 |_ templates
    |_hello.html

"web模版系統" 是指一個變量部分能夠被動態替換的HTML代碼的系統. web模版系統包含一個模版引擎, 一種數據源, 和一個模版處理工具.
Flask使用Jinja2模版引擎, web模版包含有按HTML語法書寫的腳本和由變量或表達式構成的動態內容的佔位符. 這些佔位符會在模版渲染時被替換成須要展現的動態內容.
咱們能夠把以下內容保存爲hello.html:flask

<!doctype html>
<html>
   <body>
      <h1>Hello {{ name }}!</h1>
   </body>
</html>

而後運行下面的Python代碼:瀏覽器

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/<user>')
def hello_name(user):
   return render_template('hello.html', name = user)

if __name__ == '__main__':
   app.run(debug = True)

服務器在開發模式下開始運行以後, 咱們打開瀏覽器在地址欄輸入 http://localhost:5000/hello/mvl.
咱們能夠看到在模版的{{ name }} 部分, 替換成了變量mvl.
Jinja2使用以下的佔位符語法:服務器

  • {% ... %} 聲明
  • {{ ... }} 用於表達式直接把結果輸出
  • {# ... #} 用於註釋, 將不會在模版引擎渲染結果中輸出
  • # ... ## 行註釋

下面的例子展現了模版中條件語句的使用.
hello_name()方法接收一個整型參數, 傳遞給hello.html模版, 其中, masks變量接受到了這個整型變量, 並進行判斷比較, 是否大於50, 而後進行不一樣的渲染.app

Python程序以下:函數

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/hello/<int:score>')
def hello_name(score):
   return render_template('hello.html', marks = score)

if __name__ == '__main__':
   app.run(debug = True)

模版hello.html以下:工具

<!doctype html>
<html>
   <body>
   
      {% if marks>50 %}
      <h1> Your result is pass!</h1>
      {% else %}
      <h1>Your result is fail</h1>
      {% endif %}
      
   </body>
</html>

注意, if-else和endif語句被包裹在{%..%}之中.
啓動腳本並分別在瀏覽器輸入http://localhost/hello/60http://localhost/hello/30, 觀察模版不一樣的渲染結果.編碼

Python中的循環語法也能夠在模版中實現. 下面的程序中, 當請求 http://localhost:5000/result 時, result()方法就向模版result.html發送了一個字典對象用於渲染. 而後result.html使用for循環把字典result的鍵值對渲染到html表格中.

Python程序以下:

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/result')
def result():
   dict = {'phy':50,'che':60,'maths':70}
   return render_template('result.html', result = dict)

if __name__ == '__main__':
   app.run(debug = True)

把下面result.html模版文件保存到默認templates模版文件夾中.

<!doctype html>
<html>
   <body>
   
      <table border = 1>
         {% for key, value in result.iteritems() %}
         
            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>
            
         {% endfor %}
      </table>
      
   </body>
</html>

這裏, for循環聲明語句被用{%..%}包裹了起來, 鍵值對取值的部分被用{{ }}包裹.
程序開始執行後, 咱們能夠打開瀏覽器, 看看 http://localhost:5000/result的輸出.

相關文章
相關標籤/搜索