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,代码如下: