Django在模板引擎中提供了各種機(jī)制來(lái)幫助我們實(shí)現(xiàn)這一目標(biāo)。在本教程中,我將說(shuō)明如何使用Django內(nèi)置模板標(biāo)記塊,擴(kuò)展和包含來(lái)使模板易于維護(hù)。
準(zhǔn)備工作:
1、Python 3.6
2、Django 2.2
3、AdminLTE 3.0.5
我們目標(biāo)是將模板文件有效組織起來(lái),避免重復(fù)的代碼引用,我們分四個(gè)步驟來(lái)實(shí)現(xiàn)。
步驟1/4:base.html將模板分為多個(gè)部分,我們知道除了菜單和內(nèi)容外,其他所有內(nèi)容都是可重復(fù)的。我們將制作一個(gè)基本模板來(lái)容納那些常見(jiàn)的部分,如圖:
在項(xiàng)目文件夾中創(chuàng)建一個(gè)文件夾模板。在其中創(chuàng)建一個(gè)base.html。將所有常見(jiàn)的片段添加到其中。只需復(fù)制并粘貼以下內(nèi)容,僅是load.html和index.html共享的一部分代碼。
{% load static %}AdminLTE 3 | Starter {% block content_wrapper %}{% endblock %}
請(qǐng)注意,塊content_wrapper用于呈現(xiàn)每個(gè)頁(yè)面的自定義內(nèi)容。
步驟2/4:刪除冗余的通用代碼由于我們?cè)谏弦徊街袆?chuàng)建了base.html,因此不再需要將通用代碼保留在Landing.html和home.html中。我們應(yīng)該得到如下結(jié)果。
步驟3/4:繼承base.htmllanding.html頁(yè)面代碼: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用作每個(gè)頁(yè)面的基礎(chǔ)模板,我們需要通過(guò)在模板的開(kāi)頭使用{%extended‘base.html’%}來(lái)聲明base.html為“父”模板。最重要的是,不要忘記content_wrapper塊。將全部?jī)?nèi)容包裝到該塊中。我們應(yīng)該得到如下結(jié)果。
步驟4/4:將常見(jiàn)的內(nèi)容單獨(dú)存放landing.html:{% extends 'base.html' %}{% load static %}{% block content_wrapper %}. . .{% endblock %}在index.html:{% extends 'base.html' %}{% load static %}{% block content_wrapper %}. . .{% endblock %}
現(xiàn)在我們可能會(huì)意識(shí)到,兩個(gè)模板中都存在相同的巨型形式。幾乎一半的代碼是它。由于此表單已在兩個(gè)模板中重復(fù)使用,因此我們將其維護(hù)在一個(gè)可以包含任何模板的地方。
在模板文件夾中創(chuàng)建一個(gè)文件夾advanced_forms。在advanced_forms文件夾中,創(chuàng)建如下的general_elements_form.html,代碼如下: