python Django模板的使用方法(图文)
发布时间:2022-03-30 04:23:52
模版基本介绍
模板是一个文本,用于分离文档的表现形式和内容。 模板定义了占位符以及各种用于规范文档该如何显示的各部分基本逻辑(模板标签)。 模板通常用于产生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、启动服务效果如下:
猜你喜欢
- 由于个人能力有限,文章中难免会出现错误或遗漏的地方,敬请谅解!同时欢迎你指出,以便我能及时修改,以免误导下一个看官。最后希望本文能给你带来一
- 好久没有更新博客了,今天看到论坛上有位朋友问起全屏布局,有点像vc的界面。来了兴趣,就写了一个。运用IE6的怪异模式,通过绝对定位来实现的。
- 使用 Response.Redirect "aspxhome.asp" 转向方法的HTTP Status Code 为3
- 导语:目前点评“2008年10佳改版网站”也许为时尚早,但2008年毕竟已经过去了9个多月,周四又同时有Twitter和FriendFeed
- 直接看代码: 代码如下:Class GoogleTranslator sub Class_Initialize
- 本文实例讲述了php中debug_backtrace、debug_print_backtrace和匿名函数用法。分享给大家供大家参考。具体分
- 基础知识在学习该漏洞之前我们需要学习一下前置知识来更好的理解该漏洞的产生原因以及如何利用。 我们先来学习一下框架的基本信息以及反序列化漏洞的
- 将有安全问题的SQL过程删除.比较全面.一切为了安全!删除了调用shell,注册表,COM组件的破坏权限MS SQL SERVER2000使
- (一)原理 小偷程序实际上是通过了XML中的XMLHTTP组件调用其它网站上的网页。比如新闻小偷程序,
- rs.open sql,conn,A,B A: ADOPenforwardonly (=0) 只读,且当前数据记录只能向下移动。 ADOPe
- 对于数据库管理员来说,可以经常想了解一些之前未听说过的存储过程,特别是无文档类型的存储过程。或许是用这些存储过程,能够简化日常的数据管理。为
- Firefox 3 有一个很让人讨厌的bug:基于某种目的,在表单提交时 disable 掉提交按钮,通过后退键回到这个页面后,这个提交按钮
- 在网页制作中,表单中的对象总是给人一种单调与沉闷的感觉,比如说按钮、文本框等,它们一成不变的模样与颜色
- <%@ Language=VBScript %><HTML><HEAD>
- 多版本并发控制Multiversion Concurrency Control大部分的MySQL的存储 引擎,比如InnoDB,Falcon
- 方法一.Image { max-width:600px;height:
- 在这里奉上源代码,没有做样式处理,不过功能是可以的,希望大家可以和我交流交流!<html> <head>&
- 操作系统:Windows2000,IIS5出现症状:使用ASPJPEG时执行Server.CreateObject("Persit
- 本文实例讲述了PHP简单实现正则匹配省市区的方法。分享给大家供大家参考,具体如下:省市区正则匹配preg_match('/(.*?(
- 如何向客户端推送“出错信息”?下面是推送代码:服务器端:on error resume nextconn=se