Django 实现子模版继承父模板

背景

Django的占位符,如果不继承父模板的内容,会被子模版所覆盖,有些业务场景子模版也需要使用到父模板中的内容

可以使用Django自带的标签{% block super %}来实现此效果

base.html

最基础html,相当于第一层html,block js 进行占位

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- head content -->
</head>
<body>
    <!-- body content -->

    {% block js %}
    <!-- base js content -->
    <script src="base.js"></script>
    {% endblock %}
</body>
</html>

middle.html

中间html,相当于第二层html,在block js 中继承了base.html的内容

html 复制代码
{% extends "base.html" %}

{% block js %}
    {{ block.super }}
    <!-- middle js content -->
    <script src="middle.js"></script>
{% endblock %}

child.html

孩子html,相当于第三层html,在block js 中继承了middle.html的内容

html 复制代码
{% extends "middle.html" %}

{% block js %}
    {{ block.super }}
    <!-- child js content -->
    <script src="child.js"></script>
{% endblock %}

最终渲染的效果

最终能够包含所有被继承中所引入的js文件,而不是被最后一个覆盖

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <!-- head content -->
</head>
<body>
    <!-- body content -->

    <!-- base js content -->
    <script src="base.js"></script>
    <!-- middle js content -->
    <script src="middle.js"></script>
    <!-- child js content -->
    <script src="child.js"></script>
</body>
</html>
相关推荐
溪语流沙2 小时前
Django + Vue电商项目第005讲:后端骨架|Django初始化、配置分层与DRF接入
vue.js·后端·python·django
FYKJ_20104 小时前
springboot鲜花销售系统91056-计算机课程设计、毕业设计
vue.js·spring boot·后端·python·mysql·django·课程设计
言乐61 天前
Python实现ai进化
python·django·virtualenv·pygame·tornado
言乐62 天前
Python排名统计折线图
开发语言·python·django·virtualenv·pygame
Wx-bishekaifayuan2 天前
springboot户外登山社交小程序19787-计算机课程设计、毕业设计
spring boot·后端·python·spring·elasticsearch·django·课程设计
FYKJ_20102 天前
springboot刑事案件管理系统03047-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django
FYKJ_20102 天前
springboot助农产品销售商城05829-计算机课程设计、毕业设计
java·spring boot·python·mysql·spark·django
Wx-bishekaifayuan2 天前
springboot社区扶贫救助管理系统13300-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
Wx-bishekaifayuan2 天前
springboot甘肃特产服务平台50301-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
FYKJ_20102 天前
springboot雅集社区养老管理系统04456-计算机课程设计、毕业设计
vue.js·spring boot·python·mysql·typescript·spark·django