文章目录
模板继承可以减少页面内容的重复定义,实现页面内容的重用
典型应用:网站的头部、尾部是一样的,这些内容可以定义在父模板中,子模板不需要重复定义
block
标签:在父模板中预留区域,在子模板中填充extends
继承:继承,写在模板文件的第一行 1、模板继承步骤
(1)定义父模板base.html
使用%block
进行占位
{ %block block_name%}这里可以定义默认值如果不定义默认值,则表示空字符串{ %endblock%}
(2)定义子模板index.html
- 继承父模板
{ % extends "base.html" %}
- 在子模板中使用
block
填充预留区域
定义父模板中block_name
的内容
{ %block block_name%}实际填充内容{ %endblock%}
说明:
- 如果在模版中使用
extends
标签,它必须是模版中的第一个标签 - 不能在一个模版中定义多个相同名字的
block
标签 - 子模版不必定义全部父模版中的
block
,如果子模版没有定义block
,则使用了父模版中的默认值 - 如果发现在模板中大量的复制内容,那就应该把内容移动到父模板中
- 使用可以获取父模板中
block
的内容 - 为了更好的可读性,可以给
endblock
标签一个名字。
{ % block block_name %}区域内容{ % endblock block_name %}
2、使用模板继承实现练习2
分析index.html
和login.html
,发现头部和尾部是相同的,则将头部单独放在header.html
,尾部放在footer.html
,base.html
包含header.html
和footer.html
,内容使用%block
进行占位。
index2.html
继承base.html
,并定义base.html
中%block的内容。
login2.html
继承base.html
,并定义base.html
中%block的内容。
定义header.html
定义footer.html
<!-- 页脚BEGIN --><div class="bg-light border-top overflow-hidden"><p class="text-muted text-center my-3">泸州职业技术学院</p><p class="text-muted text-center mb-5">Copyright <i class="fa-solid fa-copyright"></i>20XX</p></div><!-- 页脚END -->
定义base.html
{% load static %}<!DOCTYPE html><html lang="zh"><head><!-- Required meta tags --><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"><meta http-equiv = "X-UA-Compatible" content="ie=edge"><!-- Bootstrap CSS --><link rel="stylesheet" href="{% static 'libs/bootstrap-4.5.3-dist/css/bootstrap.min.css' %}"><!-- 引入其他的第三方样式库 --><link rel="stylesheet" href="{% static 'libs/fontawesome-free-6.1.1-web/css/all.min.css' %}"><!-- 引入自定义的样式文件 --><link rel="stylesheet" href="{% static 'css/login.css' %}"><title>{% block title %}{% endblock %}</title></head><body>{% include 'exercise02/header.html' %}{% block content %}{% endblock %}{% include 'exercise02/footer.html' %}<!-- Optional JavaScript --><!-- jQuery first, then Popper.js, then Bootstrap JS --><script src="{% static 'libs/jquery-3.6.0/jquery-3.6.0.min.js' %}"></script><script src="{% static 'libs/bootstrap-4.5.3-dist/js/bootstrap.bundle.min.js' %}"></script><script src="{% static 'libs/bootstrap-4.5.3-dist/js/bootstrap.min.js' %}"></script></body></html>
定义index02.html
定义login2.html
定义路由和视图进行访问
path('index02/',views.index02,name='index02'),path('login02/',views.login02,name='login02'),
def index02(request):return render(request,'exercise02/index2.html')def login02(request):return render(request,'exercise02/login2.html')
访问查看效果
修改index2.html和login2.html
<a class="nav-link" href="{% url 'exercise02:index02' %}"> <i class="fa-solid fa-house-user"></i> 首页</a>
<a class="dropdown-item" href="{%url 'exercise02:login02' %}"><i class="fa-solid fa-users"></i> 登录</a>