千锋教育-做有情怀、有良心、有品质的职业教育机构

手机站
千锋教育

千锋学习站 | 随时随地免费学

千锋教育

扫一扫进入千锋手机站

领取全套视频
千锋教育

关注千锋学习站小程序
随时随地免费学习课程

当前位置:首页  >  技术干货  > 如何设计组织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