python测试开发django-6.模板中include使用

前言

当我们打开一个网站的时候,在打开不同的页面时候,会发现每个页面的顶部、底部内容都差不多,这样就可以把这些公共的部分,单独抽出来。
类似于python里面的函数,把公共部分写成函数,然后调用就行了,这样就能实现代码的复用。django里面也有类似的功能,用include可以实现。

公共内容

如下图所示,网站的每个页面都有顶部导航,body正文,底部导航这三块内容

1070438-20181114230437332-164820633.png

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>

一般头部和底部是不变的,变的只是body里面内容,这样把头部和底部单独抽出来

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>

include语法

hello/templates/page1.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

{% include 'top.html' %}
<section>
    <h1>body正文</h1>
    <p>正文内容</p>
</section>
{% include 'end.html' %}

</body>
</html>

hello/views.py视图函数

from django.shortcuts import render

# Create your views here.

def page1(request):
    return render(request, 'page1.html')

urls.py添加访问路径

from django.conf.urls import url
from django.urls import re_path, path
from hello import views
urlpatterns = [
    path("page1/", views.page1),
]

浏览器访问地址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": "yoyo"}
    return render(request, 'page1.html', context)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值