django框架学习:六.模板中的include的使用

前言

当我们打开一个网站时,发现每个页面的顶部底部内容差不多,为了提高代码的复用性,我们可以将这些头部,底部的代码单独封装成公用的,类似于python里封装的函数,使用的时候调用就可以了,django里有类似的功能, include实现。

公共内容 

每个网站的页面一般都有,顶部导航栏,中间页面内容,底部有一些友情链接。在设计过程中可以把这些分开编写代码。

hello/templates/top.html单独拿出来

<section>

<h1>顶部导航

</h1>

<p>python自动化-北京-流水</p> <hr>

</section>

hello/templates/end.html单独拿出来

<section>

<br><br><br><br><hr>

<h1>底部导航</h1>

<p>底部一些友情链接啊</p>

</section>

hello/templates/base.html内容

!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Title</title>

</head>

<body>

<section>

<h1>顶部导航</h1>

<p>python自动化-北京-流水</p> <hr>

</section>

<section>

<h1>body正文</h1>

<p>正文内容</p>

</section>

<section>

<br>

<br>

<br>

<br>

<hr>

<h1>底部导航</h1>

<p>底部一些友情链接啊</p> </section>

</body>

</html>

include语法

hello/templates/page1.html

 hello/views.py视图函数

urls.py添加访问路径

 

浏览器访问地址http://127.0.0.1:8000/page1/就能看的效果了

带参数

公共部分top.html和end.html里面也可以传变量,如

<section>

<h1>顶部导航</h1>

<p>python自动化-{{name}}</p> <hr>

</section>

对应视图函数

def page1(request):

       context = {"name": "流水"}

  return render(request, 'page1.html', context)

猜你喜欢

转载自www.cnblogs.com/liushui0306/p/12553551.html