我们如何实现模板的复用;
一、模板的导入
一个网站中的多个网页,如果有大量重复的内容,我们只需要写一次重复的模板,以后只要重复调用这个模板即可,这样能大大提高开发效率。
调用方法:
{% include 'header.html'%}
在导入模板的时候如果需要传递参数进去,可以使用with关键字。
{% include 'header.html' with pageindex='1' %}
二、模板的抽象
在views里我们可以定义一个抽象的数据字典,数据字典中定义页面中要显示的数据值、静态文件路径,文本内容。
data = {
'index': {'pageindex': 0, 'img': 'img/index.png', 'content': '首页的具体内容'},
'movie': {'pageindex': 2, 'img': 'img/movie.png', 'content': '电影的具体内容'},
'tv': {'pageindex': 1, 'img': 'img/tv.png', 'content': '电视剧的具体内容'},
'cartoon': {'pageindex': 3, 'img': 'img/cartoon.png', 'content': '动画的具体内容'},
}
然后在各自渲染网页的方法里使用同一个模板html文件,不过每一个方法的context参数传递的是其数据字典相对应的索引值。
def index(request):
return render(request, 'index.html', context=data['index'])
def tv(request):
return render(request, 'index.html', context=data['tv'])
def movie(request):
return render(request, 'index.html', context=data['movie'])
def cartoon(request):
return render(request, 'index.html', context=data['cartoon'])
在网页html中,原本我们需要多次重复写的内容,现在只需要用变量名替代了,html会自动根据传递进来的变量值来做对应的内容显示。
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>首页</title>
<link type="text/css" rel="stylesheet" href="{% static 'css/basic.css' %}">
</head>
<body>
<div>{% include 'header.html' with pageindex=pageindex %}</div>
<div id="big_img">
<div>
<img src="{% static img %}" alt="">
</div>
</div>
<div id="container01">
<div>{{ content }}</div>
</div>
<div>{% include 'footer.html' %}</div>
</body>
</html>
效果演示:

三、模板的继承
为了高效率地加载页面,除了使用include导入页面,也可以使用extend继承之前的页面。
使用方法
使用关键字extend
导入页面。在一个新的html中,只需要使用
{% extend 'base.html' %}
就可以完整的继承base.html中的内容。如果我们希望在新的页面中对原始的内容有所添加,我们就需要在就的base.html中保留一个block缺口,格式是:{% block 缺口名 %}
后面的继承的新页面如果需要进一步完善就是对这个缺口进行完善。
{% block img %}
{% endblock %}
后续要进行补充的内容,就写在新的html页面的block缺口中
{% extends 'base.html' %}
{% load static %}
{% block img %}
<div>
<img src="{% static 'img/index.png' %}">
</div>
{% endblock %}
网友评论