千鋒教育-做有情懷、有良心、有品質的職業教育機構

手機站
千鋒教育

千鋒學習站 | 隨時隨地免費學

千鋒教育

掃一掃進入千鋒手機站

領取全套視頻
千鋒教育

關注千鋒學習站小程序
隨時隨地免費學習課程

當前位置:首頁  >  技術干貨  > 如何設計組織Django模板

如何設計組織Django模板

來源:千鋒教育
發布人:xqq
時間: 2023-12-06 04:00:49 1701806449

Django在模板引擎中提供了各種機制來幫助我們實現這一目標。在本教程中,我將說明如何使用Django內置模板標記塊,擴展和包含來使模板易于維護。

準備工作:

1、Python 3.6

2、Django 2.2

3、AdminLTE 3.0.5

我們目標是將模板文件有效組織起來,避免重復的代碼引用,我們分四個步驟來實現。

步驟1/4:base.html

將模板分為多個部分,我們知道除了菜單和內容外,其他所有內容都是可重復的。我們將制作一個基本模板來容納那些常見的部分,如圖:

在項目文件夾中創建一個文件夾模板。在其中創建一個base.html。將所有常見的片段添加到其中。只需復制并粘貼以下內容,僅是load.html和index.html共享的一部分代碼。

 
{% load static %}        AdminLTE 3 | Starter            

請注意,塊content_wrapper用于呈現每個頁面的自定義內容。

步驟2/4:刪除冗余的通用代碼

由于我們在上一步中創建了base.html,因此不再需要將通用代碼保留在Landing.html和home.html中。我們應該得到如下結果。

 

Polls Index Page

Card title

Some quick example text to build on the card title and make up the bulk of the card's content.

Card link Another link
Card title

Some quick example text to build on the card title and make up the bulk of the card's content.

Card link Another link

General Elements

Featured
Special title treatment

With supporting text below as a natural lead-in to additional content.

Go somewhere
Featured
Special title treatment

With supporting text below as a natural lead-in to additional content.

Go somewhere
landing.html頁面代碼:

Home Landing Page

Card title

Some quick example text to build on the card title and make up the bulk of the card's content.

Card link Another link
Card title

Some quick example text to build on the card title and make up the bulk of the card's content.

Card link Another link

General Elements

步驟3/4:繼承base.html

為了將base.html用作每個頁面的基礎模板,我們需要通過在模板的開頭使用{%extended‘base.html’%}來聲明base.html為“父”模板。最重要的是,不要忘記content_wrapper塊。將全部內容包裝到該塊中。我們應該得到如下結果。

 
landing.html:{% extends 'base.html' %}{% load static %}{% block content_wrapper %}  
. . .
{% endblock %}在index.html:{% extends 'base.html' %}{% load static %}{% block content_wrapper %}
. . .
{% endblock %}

步驟4/4:將常見的內容單獨存放

現在我們可能會意識到,兩個模板中都存在相同的巨型形式。幾乎一半的代碼是它。由于此表單已在兩個模板中重復使用,因此我們將其維護在一個可以包含任何模板的地方。

在模板文件夾中創建一個文件夾advanced_forms。在advanced_forms文件夾中,創建如下的general_elements_form.html,代碼如下:

 
tags: IT培訓
聲明:本站稿件版權均屬千鋒教育所有,未經許可不得擅自轉載。
10年以上業內強師集結,手把手帶你蛻變精英
請您保持通訊暢通,專屬學習老師24小時內將與您1V1溝通
免費領取
今日已有369人領取成功
劉同學 138****2860 剛剛成功領取
王同學 131****2015 剛剛成功領取
張同學 133****4652 剛剛成功領取
李同學 135****8607 剛剛成功領取
楊同學 132****5667 剛剛成功領取
岳同學 134****6652 剛剛成功領取
梁同學 157****2950 剛剛成功領取
劉同學 189****1015 剛剛成功領取
張同學 155****4678 剛剛成功領取
鄒同學 139****2907 剛剛成功領取
董同學 138****2867 剛剛成功領取
周同學 136****3602 剛剛成功領取
相關推薦HOT
久久亚洲中文字幕精品一区四,亚洲日本另类欧美一区二区,久久久久久久这里只有免费费精品,高清国产激情视频在线观看
日本天堂久久久 | 久久久亚洲综合久久久久87 | 色狠狠一区二区三区熟女91 | 中文字幕乱码久久午夜 | 亚洲AV第二区国产精品 | 午夜福利国产在线观看 |