Django框架(九):模板之继承标签extend和添加标签include

本文介绍在Web开发中如何使用HTML模板继承,通过示例展示如何避免重复代码,提高开发效率。利用{% block %}

一、什么情况下需要使用继承?

附加html脚本:我们可以复制下面的代码到学生管理对应的html中,然后修改content部分;但是过于繁琐!所以需要使用继承!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        body,html{
            height: 100%;
            width: 100%;
        }
        .outer{display: flex;flex-direction: column;height: 100%}
        .middle{flex: 1;display: flex; background-color: white}
        .content{flex: 1; background: aliceblue;}
        .nav{
            display: flex;
            line-height: 40px;
            width: 100%;
            background-color: cadetblue;
            color: white;
            font-size: 24px;
            justify-content: center;
        }
        .left {
            width: 13%;
            background: cornflowerblue;
            overflow: auto;
            background-color: lightgrey;

        }
        .manage{
            display: flex;
            flex-direction: column;
            width:100%;
            height: 10%;
            background-color: lightseagreen;
            justify-content: center;
            align-items: center;
            margin-top: 10px;
            font-size:18px ;
            font-family: "Times New Roman";
        }
        a{
            text-decoration: none;
        }
        .manage:hover{
            background-color: darkcyan;
            font-size: 20px;

        }
        h1{
            text-align: center;
        }
    </style>
</head>
<body>
<div class="outer">
    <div class="nav">标题</div>
    <div class="middle">
        <div class="left">
            <div class="student manage"><a href="/student/">学生管理</a></div>
            <div class="teacher manage"><a href="#">老师管理</a></div>
            <div class="course manage"><a href="#">课程管理</a></div>
            <div class="classes manage"><a href="#">课程管理</a></div>
        </div>
         <div class="content">
            <h1>WELCOME TO maoniuchuxing!!!</h1>
        </div>
    </div>

</div>
</body>
</html>

二、extend

为了避免复制同样的html脚本,我们只需要将需要变动的内容设置为一个格子:

{%  block   格子名称%}

……各种html标签内容……

{%endblock%}

然后,在下一个跳转页html文件中,继承,并修改格子内容为该页面要线上的内容;

{% extends "base.html" %}


{% block content %}
    {% for student in student_list %}
        <h2>学生{{ student }}</h2>
    {% endfor %}
{% endblock %}

截图说明:

1.创建一个基础页面:

2.其他html页面来继承:

3.extend使用说明:

{%extends%}在模板中使用,必须放在第一行,否则无效;

基础模板中的{%block%}标签越多越好,这样后面的继承就会更灵活;

不允许在同一个模板中定义多个同名的{%block%}

三、include的使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冷凝娇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值