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 {% block content_wrapper %}{% endblock %}
請注意,塊content_wrapper用于呈現每個頁面的自定義內容。
步驟2/4:刪除冗余的通用代碼由于我們在上一步中創建了base.html,因此不再需要將通用代碼保留在Landing.html和home.html中。我們應該得到如下結果。
步驟3/4:繼承base.htmllanding.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 linkCard title
Some quick example text to build on the card title and make up the bulk of the card's content.
Card link Another linkGeneral Elements
Featured
Special title treatment
With supporting text below as a natural lead-in to additional content.
Go somewhereFeatured
Special title treatment
With supporting text below as a natural lead-in to additional content.
Go somewhereHome 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 linkCard title
Some quick example text to build on the card title and make up the bulk of the card's content.
Card link Another linkGeneral Elements
為了將base.html用作每個頁面的基礎模板,我們需要通過在模板的開頭使用{%extended‘base.html’%}來聲明base.html為“父”模板。最重要的是,不要忘記content_wrapper塊。將全部內容包裝到該塊中。我們應該得到如下結果。
步驟4/4:將常見的內容單獨存放landing.html:{% extends 'base.html' %}{% load static %}{% block content_wrapper %}. . .{% endblock %}在index.html:{% extends 'base.html' %}{% load static %}{% block content_wrapper %}. . .{% endblock %}
現在我們可能會意識到,兩個模板中都存在相同的巨型形式。幾乎一半的代碼是它。由于此表單已在兩個模板中重復使用,因此我們將其維護在一個可以包含任何模板的地方。
在模板文件夾中創建一個文件夾advanced_forms。在advanced_forms文件夾中,創建如下的general_elements_form.html,代碼如下: