pythonDjango模板的使用方法(图文)
模版基本介绍
模板是一个文本,用于分离文档的表现形式和内容。模板定义了占位符以及各种用于规范文档该如何显示的各部分基本逻辑(模板标签)。模板通常用于产生HTML,但是Django的模板也能产生任何基于文本格式的文档。
来一个项目说明
1、建立MyDjangoSite项目具体不多说,参考前面。
2、在MyDjangoSite(包含四个文件的)文件夹目录下新建templates文件夹存放模版。
3、在刚建立的模版下建模版文件user_info.html
<html>
<metahttp-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}}叫做模版变量;{%ifxx%},{%forxinlist%}模版标签。
4、修改settings.py中的TEMPLATE_DIRS
导入importos.path
添加os.path.join(os.path.dirname(__file__),"templates").replace("\\","/"),
TEMPLATE_DIRS=(
#Putstringshere,like"/home/html/django_templates"or"C:/www/django/templates".
#Alwaysuseforwardslashes,evenonWindows.
#Don"tforgettouseabsolutepaths,notrelativepaths.
#"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:setfileencoding=utf-8:
#fromdjango.template.loaderimportget_template
#fromdjango.templateimportContext
#fromdjango.httpimportHttpResponse
fromdjango.shortcutsimportrender_to_response
defuser_info(request):
name="zbw"
age=24
#t=get_template("user_info.html")
#html=t.render(Context(locals()))
#returnHttpResponse(html)
returnrender_to_response("user_info.html",locals())
说明:Django模板系统的基本规则:写模板,创建Template对象,创建Context,调用render()方法。
可以看到上面代码中注释部分
#t=get_template("user_info.html")#html=t.render(Context(locals()))
#returnHttpResponse(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_responseDjango为此提供了一个捷径,让你一次性地载入某个模板文件,渲染它,然后将此作为HttpResponse返回。
6、修改urls.py
fromdjango.conf.urlsimportpatterns,include,url
fromMyDjangoSite.viewsimportuser_info
#Uncommentthenexttwolinestoenabletheadmin:
#fromdjango.contribimportadmin
#admin.autodiscover()
urlpatterns=patterns("",
#Examples:
#url(r"^$","MyDjangoSite.views.home",name="home"),
#url(r"^MyDjangoSite/",include("MyDjangoSite.foo.urls")),
#Uncommenttheadmin/doclinebelowtoenableadmindocumentation:
#url(r"^admin/doc/",include("django.contrib.admindocs.urls")),
#Uncommentthenextlinetoenabletheadmin:
#url(r"^admin/",include(admin.site.urls)),
url(r"^u/$",user_info),
)
7、启动开发服务器
基本一个简单的模版应用就完成,启动服务看效果!
效果如图:
模版的继承
减少重复编写相同代码,以及降低维护成本。直接看应用。
1、新建/templates/base.html
<html>
<metahttp-equiv="Content-type"content="text/html;charset=utf-8">
<title>{%blocktitle%}{%endblock%}</title>
<head></head>
<body>
<h3>{%blockheadTitle%}{%endblock%}</h3>
{%blockcontent%}{%endblock%}
{%blockfooter%}
<h3>嘿,这是继承了模版</h3>
{%endblock%}
</body>
</html>
2、修改/template/user_info.html,以及新建product_info.html
urser_info.html
{%extends"base.html"%}
{%blocktitle%}用户信息{%endblock%}
<h3>{%blockheadTitle%}用户信息:{%endblock%}</h3>
{%blockcontent%}
<p>姓名:{{name}}</p>
<p>年龄:{{age}}</p>
{%endblock%}
product_info.html
{%extends"base.html"%}
{%blocktitle%}产品信息{%endblock%}
<h3>{%blockheadTitle%}产品信息:{%endblock%}</h3>
{%blockcontent%}
{{productName}}
{%endblock%}
3、编写视图逻辑,修改views.py
#vim:setfileencoding=utf-8:
#fromdjango.template.loaderimportget_template
#fromdjango.templateimportContext
#fromdjango.httpimportHttpResponse
fromdjango.shortcutsimportrender_to_response
defuser_info(request):
name="zbw"
age=24
#t=get_template("user_info.html")
#html=t.render(Context(locals()))
#returnHttpResponse(html)
returnrender_to_response("user_info.html",locals())
defproduct_info(request):
productName="阿莫西林胶囊"
returnrender_to_response("product_info.html",{"productName":productName})
4、修改urls.py
fromdjango.conf.urlsimportpatterns,include,url
fromMyDjangoSite.viewsimportuser_info,product_info
#Uncommentthenexttwolinestoenabletheadmin:
#fromdjango.contribimportadmin
#admin.autodiscover()
urlpatterns=patterns("",
#Examples:
#url(r"^$","MyDjangoSite.views.home",name="home"),
#url(r"^MyDjangoSite/",include("MyDjangoSite.foo.urls")),
#Uncommenttheadmin/doclinebelowtoenableadmindocumentation:
#url(r"^admin/doc/",include("django.contrib.admindocs.urls")),
#Uncommentthenextlinetoenabletheadmin:
#url(r"^admin/",include(admin.site.urls)),
url(r"^u/$",user_info),
url(r"^p/$",product_info),
)
5、启动服务效果如下:
相关文章
- AI Codec,视频模板技术,高效视频处理,RTC+AI,感知编码,CV-CUDA,窄带高清AI
- Excel VBA自定义模板(Label)标签生成工具
- Maven的SSM依赖导入基本模板
- Vue源码之mustache模板引擎(一)
- 【GoF 23】篇6:模板方法
- 23种设计模式之 : 模板方法设计模式
- 【Kotlin】Kotlin 常用表达式 ( range 范围表达式 | when 条件表达式 | 字符串模板 )
- 【C++】模板进阶
- 模板层面向typecho编辑器页面插入代码
- PHP.MVC的模板标签系统(三)
- 不用模板只用ASP+FSO生成静态HTML页的一个方法
- 在PHP世界中选择最合适的模板与使用方法
- asp.netTemplateField模板中的Bind方法和Eval方法
- 在smarty模板中使用PHP函数的方法
- 使ecshop模板中可引用常量的实现方法
- 用函数模板,写一个简单高效的JSON查询器的方法介绍
- Jquery模板数据绑定插件的使用方法详解
- sae使用smarty模板的方法
- python中使用sys模板和logging模块获取行号和函数名的方法
- smarty模板局部缓存方法使用示例
- ThinkPHP模板自定义标签使用方法
- web.py中调用文件夹内模板的方法