1. 程式人生 > >Flask ~~“一見鍾情之初體驗”(flask的網頁模板介紹及使用①)

Flask ~~“一見鍾情之初體驗”(flask的網頁模板介紹及使用①)

                                                                                 模板

模板:其實是一個包含響應文字的檔案,其中用佔位符(變數)表示動態部分,

告訴模板引擎其具體的值需要從使用的資料中獲取
使用真實值替換變數,再返回最終得到的字串,這個過程稱為“渲染”
Flask是使用 Jinja2 這個模板引擎來渲染模板

使用模板的好處:

檢視函式只負責業務邏輯和資料處理(業務邏輯方面)
而模板則取到檢視函式的資料結果進行展示(檢視展示方面)
程式碼結構清晰,耦合度低。

瞭解了什麼是模板以及模板的作用,下面我們來看看模板的簡單語法使用:

在使用網頁模板首先我們要匯入:

from flask import Flask,render_template

Flask提供的 render_template 函式封裝了該模板引擎
render_template 函式的第一個引數是模板的檔名,後面的引數都是鍵值對,表示模板中變數對應的真實值。

程式碼如下:

# -*- encoding: utf-8 -*-

#網頁模板需要匯入render_template
from flask import Flask,render_template

#建立物件
app=Flask(__name__)

@app.route('/')
def index():
    my_str = '你好世界'
    my_int=123
    my_list=['','','','','','','']
    my_dict={'name':'xiaowang'}
    context={}
    context['my_str
']=my_str context['my_int']=my_int context['my_list']=my_list context['my_dict']=my_dict #使用render_tempate模板來渲染檔案,通過第二個引數傳遞資料變數 # return render_template('day3.html',my_str=my_str,my_int=my_int,my_list=my_list,my_dict=my_dict)
   #下面還有一種比較簡單的方法:
#通過**引用來巢狀dict直接傳遞給模板 return render_template('day3.html',**context) if __name__ == "__main__": app.run( debug=True)

現在我們要在專案下建立 templates 資料夾,用於存放所有的模板檔案,並在目錄下建立一個模板html檔案。

程式碼如下:

在寫程式碼的時候我先來介紹幾個小語法:

{{ }} 來表示變數名,這種 {{ }} 語法叫做變數程式碼塊
用 {% %} 定義的控制程式碼塊,可以實現一些語言層次的功能,比如迴圈或者if語句
使用 {#  #} 進行註釋,註釋的內容不會在html中被渲染出來

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>flask網頁模板學習</title>
  </head>
  <body>
    <div>
      這是我們第一個網頁模板<br />
      {# 這裡是註釋,最基本的模板語法輸出一個變數 #} <br />
      {{ my_str }} <br />

      {# 模板語法可以做簡單的運算操作 #} <br />
      {{ my_int + 10 }}

      {# 模板語法可以用下標引用的方式輸出list元素#} <br />
      {{ my_list }} <br />
      {# 模板語法可以通過呼叫key來輸出value#}<br />

      {{ my_dict["name"] }}

      {# 使用{%%}來定義簡單的邏輯控制程式碼 #}

      {% if my_int%} 整形存在 {% else%}
      不存在 
      {# 使用if判斷,一定要有endif 來結束判斷#} 
      {% endif%}
      <ul>
        {# 使用for迴圈來遍歷list#} {% for i in my_list%}
        <li>{{ i }}</li>
        {%endfor%}
      </ul>

      {# 使用 if for 巢狀來實現單雙行背景色#}

      <table style="border:1px solid yellow">
        {% for item in my_list%} {#
        使用loop關鍵字可以呼叫迴圈的索引,來判斷下標單雙#}
         {% if loop.index % 2 == 0%}
        <tr style="background-color:red">
          <td>{{ item }}</td>
        </tr>
        {% else %}
        <tr style="background-color:blue">
          <td>{{ item }}</td>
        </tr>
        {% endif %}
         
        {% endfor %}
      </table>
    </div>
  </body>
</html>

這裡有幾個注意點:

在使用 if 判斷完畢後一定要有 endif 來結束

在使用 for 迴圈完畢後 也需要 endfor 來結束

{{ }} 來表示變數名
{% %} 可以實現一些語言層次的功能,比如迴圈或者if語句
{#  #} 進行註釋

這幾個基本格式千萬要仔細 不能出錯。

 

網頁模板的基本使用還有很多很多  這次就先寫到這,下次繼續補充。