python Django模板的使用方法
作者:lijiao 发布时间:2021-06-09 15:29:14
模板是一个文本,用于分离文档的表现形式和内容。 模板定义了占位符以及各种用于规范文档该如何显示的各部分基本逻辑(模板标签)。 模板通常用于产生HTML,但是Django的模板也能产生任何基于文本格式的文档。
来一个项目说明
1、建立MyDjangoSite项目具体不多说,参考前面。
2、在MyDjangoSite(包含四个文件的)文件夹目录下新建templates文件夹存放模版。
3、在刚建立的模版下建模版文件user_info.html
<html>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>用户信息</title>
<head></head>
<body>
<h3>用户信息:</h3>
<p>姓名:{{name}}</p>
<p>年龄:{{age}}</p>
</body>
</html>
说明:{{ name }}叫做模版变量;{% if xx %} ,{% for x in list %}模版标签。
4、修改settings.py 中的TEMPLATE_DIRS
导入import os.path
添加 os.path.join(os.path.dirname(__file__), ‘templates').replace(‘\\','/'),
TEMPLATE_DIRS = (
# Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
#"E:/workspace/pythonworkspace/MyDjangoSite/MyDjangoSite/templates",
os.path.join(os.path.dirname(__file__), 'templates').replace('\\','/'),
)
说明:指定模版加载路径。其中os.path.dirname(__file__)为当前settings.py的文件路径,再连接上templates路径。
5、新建视图文件view.py
#vim: set fileencoding=utf-8:
#from django.template.loader import get_template
#from django.template import Context
#from django.http import HttpResponse
from django.shortcuts import render_to_response
def user_info(request):
name = 'zbw'
age = 24
#t = get_template('user_info.html')
#html = t.render(Context(locals()))
#return HttpResponse(html)
return render_to_response('user_info.html',locals())
说明:Django模板系统的基本规则: 写模板,创建 Template 对象,创建 Context , 调用 render() 方法。
可以看到上面代码中注释部分
#t = get_template(‘user_info.html') #html = t.render(Context(locals()))
#return HttpResponse(html)
get_template(‘user_info.html'),使用了函数 django.template.loader.get_template() ,而不是手动从文件系统加载模板。 该 get_template() 函数以模板名称为参数,在文件系统中找出模块的位置,打开文件并返回一个编译好的 Template 对象。
render(Context(locals()))方法接收传入一套变量context。它将返回一个基于模板的展现字符串,模板中的变量和标签会被context值替换。其中Context(locals())等价于Context({‘name':'zbw','age':24}) ,locals()它返回的字典对所有局部变量的名称与值进行映射。
render_to_response Django为此提供了一个捷径,让你一次性地载入某个模板文件,渲染它,然后将此作为 HttpResponse返回。
6、修改urls.py
from django.conf.urls import patterns, include, url
from MyDjangoSite.views import user_info
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'MyDjangoSite.views.home', name='home'),
# url(r'^MyDjangoSite/', include('MyDjangoSite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^u/$',user_info),
)
7、启动开发服务器
基本一个简单的模版应用就完成,启动服务看效果!
效果如图:
模版的继承
减少重复编写相同代码,以及降低维护成本。直接看应用。
1、新建/templates/base.html
<html>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>{% block title %}{% endblock %}</title>
<head></head>
<body>
<h3>{% block headTitle %}{% endblock %}</h3>
{% block content %} {% endblock %}
{% block footer %}
<h3>嘿,这是继承了模版</h3>
{% endblock%}
</body>
</html>
2、修改/template/user_info.html,以及新建product_info.html
urser_info.html
{% extends "base.html" %}
{% block title %}用户信息{% endblock %}
<h3>{% block headTitle %}用户信息:{% endblock %}</h3>
{% block content %}
<p>姓名:{{name}}</p>
<p>年龄:{{age}}</p>
{% endblock %}
product_info.html
{% extends "base.html" %}
{% block title %}产品信息{% endblock %}
<h3>{% block headTitle %}产品信息:{% endblock %}</h3>
{% block content %}
{{productName}}
{% endblock %}
3、编写视图逻辑,修改views.py
#vim: set fileencoding=utf-8:
#from django.template.loader import get_template
#from django.template import Context
#from django.http import HttpResponse
from django.shortcuts import render_to_response
def user_info(request):
name = 'zbw'
age = 24
#t = get_template('user_info.html')
#html = t.render(Context(locals()))
#return HttpResponse(html)
return render_to_response('user_info.html',locals())
def product_info(request):
productName = '阿莫西林胶囊'
return render_to_response('product_info.html',{'productName':productName})
4、修改urls.py
from django.conf.urls import patterns, include, url
from MyDjangoSite.views import user_info,product_info
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'MyDjangoSite.views.home', name='home'),
# url(r'^MyDjangoSite/', include('MyDjangoSite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
# url(r'^admin/', include(admin.site.urls)),
url(r'^u/$',user_info),
url(r'^p/$',product_info),
)
5、启动服务效果如下:
猜你喜欢
- Python中的闭包前几天又有人留言,关于其中一个闭包和re.sub的使用不太清楚。我在脚本之家搜索了下,发现没有写过闭包相关的东西,所以决
- 你的主页或者你管理的网站有各种密码需要保护,把密码直接放在数据库或者文件中存在不少安全隐患,所以密码加密后存储是最常见的做法。在ASP.NE
- 有效地加载数据有时我们需大量地把数据加载到数据表,采用批量加载的方式比一个一个记录加载效率高,因为MySQL不用每加载一条记录就刷新一次索引
- CSS2.1 中规定了关于 CSS 规则 Specificity(特异性)的计算方式,用一个四位的数
- 因为固体物理书上的球面投影图太难看,就自学 javascipt 用 echarts 做了个可交互的,效果如下:上面为立方晶系主要晶面(晶向)
- 测试环境为Windows 10 系统,Python3.7,转换需要提前安装pydub、ffmpeg,安装和加入环境变量配置方法自行解决,至于
- 这篇文章主要介绍了python如何实现不可变字典inmutabledict,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参
- 本文实例讲述了python实现复制整个目录的方法。分享给大家供大家参考。具体分析如下:python有一个非常好用的目录操作类库shutil,
- 我认为在ASP中最好的办法是用编程实现定时刷新Cache,也就是说给Application中储存的设一个过期时间。当然,在ASP中Appli
- MySql5.0以后均支持存储过程,最近有空,研究了一把这个。格式:以下为引用的内容:CREATE PROCEDURE
- 我认为多选列表具有完美的功能——只需按下Ctrl键,同时点击鼠标从列表中选择多个项目。以下是一个典型的多选列表框:选出你最喜爱的快餐:&nb
- 前言夏天是用来告别的季节,因为毕业总在七月。那么七月之前的季节是用来干嘛的呢?当然是用来做毕业设计的啦今天还是写一些从简单到难的毕业设计或者
- 本文实例讲述了Python基于time模块求程序运行时间的方法。分享给大家供大家参考,具体如下:要记录程序的运行时间可以利用Unix系统中,
- 今天我想讲一讲关于Elasticsearch的索引建立,当然提前是你已经安装部署好Elasticsearch。ok,先来介绍一下Elatic
- MYSQL数据库安装完成后,默认最大连接数是100,一般流量稍微大一点的论坛或网站这个连接数是远远不够的,增加默认MYSQL连接数的方法有两
- 本文实例讲述了Python反转序列的方法。分享给大家供大家参考,具体如下:序列是python中最基本的数据结构,序列中每个元素都有一个跟位置
- 使用python基于cartopy库绘制台风路径使用python 绘制西太平洋进入我国的台风路径,文件为.dat格式,内容如下所示:代码如下
- 1、唠唠叨叨最近项目中需要Python的打包,看到网上也没有很详细的资料,于是做了一些示例程序。小小的研究了一下,Python如何在Wind
- 注:本文所指的YUV均为YUV420中的I420格式(最常见的一种),其他格式不能用以下的代码。位深为8bit时,每个像素占用1字节,对应文
- 我的Windows 8.1 环境1.下载安装Python 2.7.6在Python官方网站中下载Python2.7.6的Windows安装包