博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python测试开发django-6.模板中include使用
阅读量:6941 次
发布时间:2019-06-27

本文共 1322 字,大约阅读时间需要 4 分钟。

前言

当我们打开一个网站的时候,在打开不同的页面时候,会发现每个页面的顶部、底部内容都差不多,这样就可以把这些公共的部分,单独抽出来。

类似于python里面的函数,把公共部分写成函数,然后调用就行了,这样就能实现代码的复用。django里面也有类似的功能,用include可以实现。

公共内容

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

1070438-20181114230437332-164820633.png

hello/templates/base.html内容

    
Title

顶部导航

python自动化-上海-悠悠


body正文

正文内容


底部导航

底部一些友情链接啊,网站导航,版权啊

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

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

顶部导航

python自动化-上海-悠悠


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


底部导航

底部一些友情链接啊,网站导航,版权啊

include语法

hello/templates/page1.html

    
Title{% include 'top.html' %}

body正文

正文内容

{% include 'end.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 urlfrom django.urls import re_path, pathfrom hello import viewsurlpatterns = [    path("page1/", views.page1),]

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

带参数

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

顶部导航

python自动化-{

{name}}


对应视图函数

def page1(request):    context = {"name": "yoyo"}    return render(request, 'page1.html', context)

转载地址:http://bsinl.baihongyu.com/

你可能感兴趣的文章
一次owa登录exchange邮箱提示下载owaauth.dll的解决办法
查看>>
我的友情链接
查看>>
Log.cat 的使用
查看>>
使用myEclipse把java项目上传到码云
查看>>
Python爬虫框架Scrapy 学习笔记 5 ------- 使用pipelines过滤敏感词
查看>>
GTM+800的时间格式转成yyyy-mm-dd的格式
查看>>
QT下载地址
查看>>
sap system monitor ---- SM51 function
查看>>
网络编程服务器基础模型三(多线程模型)
查看>>
C++ MFC WebBrowser 探索(三)
查看>>
apache 禁止爬虫
查看>>
debian下LAMP+nginx代理+awstats+cacti+nagios(一)
查看>>
lib_mysqludf_json导致mysql重启原因分析
查看>>
nginx+onethink配置访问路径
查看>>
DB2_COMPATIBILITY_VECTOR=ORA, DATE type
查看>>
ip classless
查看>>
Exchange Server 2010 OWA与Lync Server 2010 IM集成
查看>>
对于NoClassDefFoundError: javax/servlet/jsp/jstl/core/Config的异常
查看>>
我的友情链接
查看>>
用Redis存储Tomcat集群的Session
查看>>