python學習第9天---django框架---模板詳解

python學習第9天---django框架---模板詳解


目錄




內容

1、模板的功能

 &emps;模板用於生產html,控制頁面展示的內容。模板文件不僅僅是html文件,模板文件包含2部分內容:

  • 靜態內容:js、css、img等等靜態資源
  • 動態內容:用於動態生成一些頁面內容,通過模板語言

2、模板文件的使用

2.1、使用步驟

  通常是通過視圖函數使用模板生成html內容返回給客戶端,步驟如下:

  1. 加載模板文件:loader.get_template,獲取模板文件內容,生成一個模板對象
  2. 定義模板上下文:Context,給模板文件傳遞數據
  3. 模板渲染產生html頁面:render,用傳遞的數據替換模板文件中的響應變量,生成替換後的html文件。

2.2、示例

  接上面書籍管理系統,我們把書籍管理系統登錄後書籍管理首頁及視圖函數,稍加修改。

  • 模板文件代碼2.2-1:index.html

      <!DOCTYPE html>
      <html lang="en">
      <head>
      	<meta charset="UTF-8">
      	<title>Title</title>
      	<style>
      		.book {
      			width: 200px;
      			height: 100px;
      			margin: 0 auto;
      		}
    
      		li {
      			color: green;
      		}
      	</style>
    
    
      </head>
      <body>
      <div class="book">
      	<h3 style="color: orange">{{ title }}首頁</h3>
      	<hr>
      	<a href="http://127.0.0.1:8000/book/book_list">{{ content }}</a>
    
      </div>
      </body>
      </html>
    
  • 視圖函數代碼2.2-2:index

      def index(request):
      # return HttpResponse('歡迎進入書籍管理系統')
      # 1、加載模板文件,生成模板對象
      temp = loader.get_template('book/index.html')
      # 2、定義模板上下文,給模板文件傳遞數據
      content = {'title': '書籍管理', 'content': '書籍列表'}
      context = Context(content)
      # 3、模板渲染,替換模板文件中響應變量,返回html內容
      res_html = temp.render(content, request)
      # 4、返回應答
      return HttpResponse(res_html)
    
  • 效果圖示2.2-1:在這裏插入圖片描述

2.3、封裝

  render函數其實已經幫我們封裝好了,直接使用就好了。代碼2.3-1:

	def index(request):
		# return HttpResponse('歡迎進入書籍管理系統')
		return render(request, 'book/index.html', {'title': '書籍管理', 'content': '書籍列表'})

結果與2.2相同,有興趣的小夥伴可以自己去查看render源代碼。

3、模板文件的加載順序

  在這裏插入圖片描述

  1. 首先去配置的模板目錄下面找模板文件

    • 當前配置目錄:

        TEMPLATES = [
        {
        	'BACKEND': 'django.template.backends.django.DjangoTemplates',
        	'DIRS': [os.path.join(BASE_DIR, 'templates')], # 當前配置模板目錄
        	'APP_DIRS': True,
        	'OPTIONS': {
        		'context_processors': [
        			'django.template.context_processors.debug',
        			'django.template.context_processors.request',
        			'django.contrib.auth.context_processors.auth',
        			'django.contrib.messages.context_processors.messages',
        		],
        	},
        },
      

      ]

  2. 去INSTALL_APPS下面的每個應用中去找模板文件,前提是應用中必須有templates文件夾

    • INSTALL_APPS:

        INSTALLED_APPS = [
        	'django.contrib.admin',  # 有templates目錄
        	'django.contrib.auth',  # 有templates目錄
        	'django.contrib.contenttypes',
        	'django.contrib.sessions',
        	'django.contrib.messages',
        	'django.contrib.staticfiles',
        	'book',  # book應用
        	'login',  # 登錄應用
      
        ]
      

4、模板語言

4.1、模板變量

  • 命名:由字母、數字和下劃線組成,不能以下劃線開頭
  • 使用:{{ var_name }}
  • 示例代碼:查看2.2-1代碼

4.2、模板標籤

4.2.1、 循環:

  • 模板示例:

      {% for book in book_list %}
      	代碼塊
      {% endfor %}
    

4.2.2、判斷

  • 模板示例:

      {% if 判斷條件 %}
      	...
      {% elif 判斷條件 %}
      	...
      {% else %}
      	...
      {% endif %}
    

4.3、過濾器

過濾器用於對模板變量操作。

  • 格式:模板變量 | 過濾器: 參數

4.3.1、常用內置過濾器

  • date:改變日期的顯示格式
  • length:求長度。字符串,元組,列表,字典。
  • default:設置模板變量的默認值。

詳細參數可以參考官方文檔,地址:https://docs.djangoproject.com/en/3.0/

4.3.2、自定義過濾器

  過濾器本身是python函數一種。我們在自定義python函數後,需要註冊才能成爲過濾器函數,並且前端頁面加載後,纔可以同內置過濾器一樣使用。

  • 步驟:

    1. 在應用下創建目錄templatetags目錄

    2. templatetags目錄下新建自定義過濾器文件filters.py(文件名非固定)

    3. 編輯文件filters.py

      • 代碼4.3.2-1:

          # 自定義過濾器
          from django import template
        
          # 創建Library對象
          register = template.Library()  # register固定名稱
        
        
          @register.filter(name='isEven')  # name可省略,默認過濾器名字爲函數名
          def isEven(num):
          	"""判斷一個數是否是偶數"""
          	return num % 2 == 0
        
    4. settings.py中註冊

      • 代碼:4.3.2-2:

          TEMPLATES = [
          	{
          		'BACKEND': 'django.template.backends.django.DjangoTemplates',
          		'DIRS': [os.path.join(BASE_DIR, 'templates')],
          		'APP_DIRS': True,
          		'OPTIONS': {
          			'context_processors': [
          				'django.template.context_processors.debug',
          				'django.template.context_processors.request',
          				'django.contrib.auth.context_processors.auth',
          				'django.contrib.messages.context_processors.messages',
          			],
          			'libraries': {
          				# 自定義過濾器
          				'filters': 'book.templatetags.filters'
          			},
          		},
        
          	},
          ]
        
    5. 前端文件加載過濾器文件filters.py

      • book_list_filter.html代碼4.3.2-3:

          <!DOCTYPE html>
          <html lang="en">
          {% load filters %}
          <head>
          	<meta charset="UTF-8">
          	<title>圖書管理系統</title>
          	<style>
          		.test {
          			width: 550px;
          			height: 100px;
          			margin: 0 auto;
          		}
        
          		li {
          			color: green;
          		}
          	</style>
          </head>
          <body>
          <div class="test">
          	<h3 style="color: orange">書籍管理首頁</h3>
          	<hr/>
          	<table border="1">
          		<thead>
          		<tr>
          			<th>ID</th>
          			<th>書籍名稱</th>
          			<th>出版時間</th>
          			<th>閱讀量</th>
          			<th>評論量</th>
          			<th>是否在售</th>
          			<th>書籍簡介</th>
          		</tr>
          		</thead>
          		<tbody>
          		{% for book in book_list %}
          		{% if book.id|isEven %}
          		<!--自定義過濾器 -->
          		<tr style="color: red">
          			<td>{{ book.id }}</td>
          			<td>{{ book.name}}</td>
          			<td>{{ book.publishing_date|date:"Y/m/d"}}</td>
          			<td>{{ book.reading_volume}}</td>
          			<td>{{ book.comment_volume}}</td>
          			{% if book.isDelete %}
          			<td>否</td>
          			{% else %}
          			<td>是</td>
          			{% endif %}
          			<td><a href="http://127.0.0.1:8000/book/book_list/{{ book.id}}">點擊查看</a></td>
          		</tr>
          		{% else %}
          		<tr style="color: green">
          			<td>{{ book.id }}</td>
          			<td>{{ book.name}}</td>
          			<td>{{ book.publishing_date|date:"Y/m/d"}}</td>
          			<td>{{ book.reading_volume}}</td>
          			<td>{{ book.comment_volume}}</td>
          			{% if book.isDelete %}
          			<td>否</td>
          			{% else %}
          			<td>是</td>
          			{% endif %}
          			<td><a href="http://127.0.0.1:8000/book/book_list/{{ book.id}}">點擊查看</a></td>
          		</tr>
          		{% endif %}
          		{% endfor %}
          		</tbody>
          	</table>
          	<a href="http://127.0.0.1:8000/book/index">返回</a>
        
          </div>
          </body>
          </html>
        
    6. 使用-同內置過濾器

  • 示例,根據書籍id的奇偶顯示不同顏色。

    • 圖示4.3.2-1:在這裏插入圖片描述

4.4、模板運算符

  • 關係運算符:<,>,==,!=,<=,>=
  • 邏輯運算符:and,or, not,in

tips:運算符前後要加空格,不然會報錯

4.5、模板註釋

  • 單行註釋:{# #}

  • 多行註釋:

      {% comment %}
      	...
      {% endcomment
    

4.5、綜合示例

  根據書籍id,顯示不同的顏色。id<=2時,顯示紅色;id<=4時,顯示綠色;其他的顯示藍色。

  • 示例代碼4.5-1:book_list_structure.html

      <!DOCTYPE html>
      <html lang="en">
      <head>
      	<meta charset="UTF-8">
      	<title>圖書管理系統</title>
      	<style>
      		.test {
      			width: 550px;
      			height: 100px;
      			margin: 0 auto;
      		}
    
      		li {
      			color: green;
      		}
      	</style>
      </head>
      <body>
      <div class="test">
      	<h3 style="color: orange">書籍管理首頁</h3>
      	<hr/>
      	<table border="1">
      		<thead>
      		<tr>
      			<th>ID</th>
      			<th>書籍名稱</th>
      			<th>出版時間</th>
      			<th>閱讀量</th>
      			<th>評論量</th>
      			<th>是否在售</th>
      			<th>書籍簡介</th>
      		</tr>
      		</thead>
      		<tbody>
      		{% for book in book_list %}
      			{% if book.id <= 2 %}
      				<tr style="color: red">
      					<td>{{ book.id }}</td>
      					<td>{{ book.name}}</td>
      					<td>{{ book.publishing_date|date:"Y/m/d"}}</td>
      					<td>{{ book.reading_volume}}</td>
      					<td>{{ book.comment_volume}}</td>
      					{% if book.isDelete %}
      					<td>否</td>
      					{% else %}
      					<td>是</td>
      					{% endif %}
      					<td><a href="http://127.0.0.1:8000/book/book_list/{{ book.id}}">點擊查看</a></td>
      				</tr>
      			{% elif book.id <= 4 %}
      				<tr style="color: green">
      					<td>{{ book.id }}</td>
      					<td>{{ book.name}}</td>
      					<td>{{ book.publishing_date|date:"Y/m/d"}}</td>
      					<td>{{ book.reading_volume}}</td>
      					<td>{{ book.comment_volume}}</td>
      					{% if book.isDelete %}
      					<td>否</td>
      					{% else %}
      					<td>是</td>
      					{% endif %}
      					<td><a href="http://127.0.0.1:8000/book/book_list/{{ book.id}}">點擊查看</a></td>
      				</tr>
      			{% else %}
      				<tr style="color: blue">
      					<td>{{ book.id }}</td>
      					<td>{{ book.name}}</td>
      					<td>{{ book.publishing_date|date:"Y/m/d"}}</td>
      					<td>{{ book.reading_volume}}</td>
      					<td>{{ book.comment_volume}}</td>
      					{% if book.isDelete %}
      					<td>否</td>
      					{% else %}
      					<td>是</td>
      					{% endif %}
      					<td><a href="http://127.0.0.1:8000/book/book_list/{{ book.id}}">點擊查看</a></td>
      				</tr>
      			{% endif %}
      		{% endfor %}
      		</tbody>
      	</table>
      	<a href="http://127.0.0.1:8000/book/index">返回</a>
    
      </div>
      </body>
      </html>
    
  • 視圖函數代碼4.5-2:

      def book_list_structure(request):
      	'''書籍列表展示'''
      	books = Book.objects.all()
      	return render(request, 'book/book_list_structure.html', {'book_list': books})
    
  • url: url(r’^book_list_structure$’, views.book_list_structure),

  • 效果圖示4.5-1:在這裏插入圖片描述

6、模板繼承

  通常網站都有一些通用的網頁部分,比如頭部導航和底部版權信息。如果,所有頁面都寫一遍,增加很多工作量。這裏使用模板繼承很方便。

  • 父模板:公用模板

    • 格式:

        # 相同內容
        ...
        # 不同內容
        {% block 塊名1 %}
        	...
        {% endblock 塊名1 %}
        {% block 塊名2 %}
        	...
        {% endblock 塊名2 %}
        ...
        ...
      
    • 解析:

      • 對於通用的內容,即爲普通的html
      • 不同的內容包裹在block塊內
      • 可以有多個block塊
  • 子模板:繼承子父模板

    • 格式

        {% extends 父模板 %}
        {% block 塊名1 %}
        	...
        {% endblock 塊名1 %}
        {% block 塊名2 %}
        	...
        {% endblock 塊名2 %}
      
    • 解析:

      • 子模板可以重新塊中的內容,也可以使用父模板原有的內容
      • block.super爲父模板塊中內容
  • 示例:pass

7、html轉義

  模板上下文中的html標記默認是會被轉義的。常見對應關係表格7-1:

顯示 說明 html編碼 16進制編碼
半方大的空白 &ensp; &#8194;
全方大的空白 &emsp; &#8195;
不斷行的空白格 &nbsp; &#160;
< 小於 &lt; &#60;
> 大於 &gt; &#62;
& &符號 &amp; &#38;
" 雙引號 &quot; &#34;
© 版權 &copy; &#169;
® 已註冊商標 &reg; &#174;
商標(美國) \™ &#8482;
× 乘號 &times; &#215;
÷ 除號 &divide; &#247;
  • 關閉自動轉義
    • 單行關閉:

        {{ 模板變量|safe}}
      
    • 多行關閉:

        {% autoescape off %}
        	...
        {% endautoescape %}
      

感興趣的小夥伴可以自行搜索,這裏不再詳述。

後記

  本項目爲參考某音python系列視頻。上面爲自己參考寫的學習筆記,持續更新。歡迎交流,本人QQ:806797785

  1. 原視頻地址:https://space.bilibili.com/277754748?spm_id_from=333.788.b_765f7570696e666f.1
  2. 筆記項目源代碼地址:https://gitee.com/gaogzhen/python
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章