python Django模板的使用方法


Posted in Python onJanuary 14, 2016

模板是一个文本,用于分离文档的表现形式和内容。 模板定义了占位符以及各种用于规范文档该如何显示的各部分基本逻辑(模板标签)。 模板通常用于产生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、启动开发服务器

基本一个简单的模版应用就完成,启动服务看效果!
效果如图:

python Django模板的使用方法

模版的继承
减少重复编写相同代码,以及降低维护成本。直接看应用。
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 Django模板的使用方法

以上就是本文的全部内容,希望对大家的学习有所帮助。

Python 相关文章推荐
vc6编写python扩展的方法分享
Jan 17 Python
pyqt4教程之实现半透明的天气预报界面示例
Mar 02 Python
python批量提交沙箱问题实例
Oct 08 Python
Python通过调用有道翻译api实现翻译功能示例
Jul 19 Python
pandas计算最大连续间隔的方法
Jul 04 Python
Python+AutoIt实现界面工具开发过程详解
Aug 07 Python
pytorch1.0中torch.nn.Conv2d用法详解
Jan 10 Python
Python用input输入列表的实例代码
Feb 07 Python
python实现飞机大战项目
Mar 11 Python
Python自动发送和收取邮件的方法
Aug 12 Python
Python类的继承super相关原理解析
Oct 22 Python
pd.drop_duplicates删除重复行的方法实现
Jun 16 Python
Python数据类型学习笔记
Jan 13 #Python
python基础入门学习笔记(Python环境搭建)
Jan 13 #Python
详解python时间模块中的datetime模块
Jan 13 #Python
Python时间模块datetime、time、calendar的使用方法
Jan 13 #Python
基于Python实现文件大小输出
Jan 11 #Python
详解Python发送邮件实例
Jan 10 #Python
python轻松查到删除自己的微信好友
Jan 10 #Python
You might like
PHP图片处理之图片背景、画布操作
2014/11/19 PHP
(currentStyle)javascript为何有时用style得不到已设定的CSS的属性
2007/08/15 Javascript
ASP 过滤数组重复数据函数(加强版)
2010/05/31 Javascript
JavaScript游戏之优化篇
2010/11/08 Javascript
jQuery的3种请求方式$.post,$.get,$.getJSON
2014/03/28 Javascript
JS对字符串编码的几种方式使用指南
2015/05/14 Javascript
使用JavaScript实现旋转的彩圈特效
2015/06/23 Javascript
Jquery中使用show()与hide()方法动画显示和隐藏图片
2015/10/08 Javascript
angularjs表格分页功能详解
2016/01/21 Javascript
谷歌showModalDialog()方法不兼容出现对话窗口的解决办法
2016/02/15 Javascript
js 原型对象和原型链理解
2017/02/09 Javascript
react-router JS 控制路由跳转实例
2017/06/15 Javascript
快速搭建React的环境步骤详解
2017/11/06 Javascript
JavaScript的setter与getter方法
2017/11/29 Javascript
在vue-cli项目中使用bootstrap的方法示例
2018/04/21 Javascript
VeeValidate在vue项目里表单校验应用案例
2018/05/09 Javascript
vue实现压缩图片预览并上传功能(promise封装)
2019/01/10 Javascript
vue二选一tab栏切换新做法实现
2021/01/19 Vue.js
在Python的Flask框架中实现单元测试的教程
2015/04/20 Python
python解决方案:WindowsError: [Error 2]
2016/08/28 Python
python利用正则表达式提取字符串
2016/12/08 Python
python利用sklearn包编写决策树源代码
2017/12/21 Python
python代码编写计算器小程序
2020/03/30 Python
Flask框架重定向,错误显示,Responses响应及Sessions会话操作示例
2019/08/01 Python
Python中IP地址处理IPy模块的方法
2019/08/16 Python
django连接mysql数据库及建表操作实例详解
2019/12/10 Python
加拿大便宜的隐形眼镜商店:Clearly
2016/09/15 全球购物
Pam & Gela官网:美国性感前卫女装品牌
2018/07/19 全球购物
Pretty Little Thing美国:时尚女性服饰
2018/08/27 全球购物
五年级科学教学反思
2014/02/05 职场文书
任命书格式
2014/06/05 职场文书
食品科学与工程专业毕业生求职信范文
2014/07/21 职场文书
市委召开党的群众路线教育实践活动总结大会报告
2014/10/21 职场文书
解除劳动关系协议书2篇
2014/11/28 职场文书
好人好事新闻稿
2015/07/17 职场文书
2016党校培训心得体会
2016/01/07 职场文书