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 相关文章推荐
Python将多个excel文件合并为一个文件
Jan 03 Python
python中yield的用法详解——最简单,最清晰的解释
Apr 04 Python
python应用文件读取与登录注册功能
Sep 23 Python
分享8点超级有用的Python编程建议(推荐)
Oct 13 Python
在Python中画图(基于Jupyter notebook的魔法函数)
Oct 28 Python
python GUI库图形界面开发之PyQt5单选按钮控件QRadioButton详细使用方法与实例
Feb 28 Python
Python 找出出现次数超过数组长度一半的元素实例
May 11 Python
pandas DataFrame运算的实现
Jun 14 Python
ffmpeg+Python实现B站MP4格式音频与视频的合并示例代码
Oct 21 Python
Python爬取梨视频的示例
Jan 29 Python
python 如何在 Matplotlib 中绘制垂直线
Apr 02 Python
Python 内置函数速查表一览
Jun 02 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面向对象全攻略 (一) 面向对象基础知识
2009/09/30 PHP
php更新mysql后获取影响的行数发生异常解决方法
2013/03/28 PHP
PHP 5.6.11中CURL模块问题的解决方法
2016/08/08 PHP
Laravel+jQuery实现AJAX分页效果
2016/09/14 PHP
Yii2实现跨mysql数据库关联查询排序功能代码
2017/02/10 PHP
PHP filter_var() 函数, 验证判断EMAIL,URL等
2021/03/09 PHP
线路分流自动跳转代码;希望对大家有用!
2006/12/02 Javascript
地震发生中逃生十大法则
2008/05/12 Javascript
让firefox支持IE的一些方法的javascript扩展函数代码
2010/01/02 Javascript
js中settimeout方法加参数
2014/02/28 Javascript
jQuery实现鼠标划过修改样式的方法
2015/04/14 Javascript
详解Javascript中的Object对象
2016/02/28 Javascript
Javascript将JSON日期格式化
2016/08/23 Javascript
JavaScript调试的多个必备小Tips
2017/01/15 Javascript
手把手15分钟搭一个企业级脚手架
2019/09/16 Javascript
React学习之JSX与react事件实例分析
2020/01/06 Javascript
JS document内容及样式操作完整示例
2020/01/14 Javascript
[01:02:46]VGJ.S vs NB 2018国际邀请赛小组赛BO2 第二场 8.18
2018/08/19 DOTA
Python浅拷贝与深拷贝用法实例
2015/05/09 Python
python中引用与复制用法实例分析
2015/06/04 Python
python实现beta分布概率密度函数的方法
2019/07/08 Python
Python3 tkinter 实现文件读取及保存功能
2019/09/12 Python
Python列表原理与用法详解【创建、元素增加、删除、访问、计数、切片、遍历等】
2019/10/30 Python
python实现银行实战系统
2020/02/26 Python
Css3新特性应用之视觉效果实例
2016/12/12 HTML / CSS
凯特·丝蓓英国官网:Kate Spade英国
2016/11/07 全球购物
欧舒丹美国官网:L’Occitane美国
2018/02/23 全球购物
JD Sports马来西亚:英国领先的运动鞋和运动服饰零售商
2018/03/13 全球购物
欧洲最大的高尔夫零售商:American Golf
2019/09/02 全球购物
如何将一个描述日期或日期/时间的字符串转换为一个Date对象
2015/10/13 面试题
汽车技术服务与营销专业推荐信
2013/11/29 职场文书
公司财务部岗位职责
2015/04/14 职场文书
教师工作证明范本
2015/06/12 职场文书
大学生党员暑假实践(活动总结)
2019/08/21 职场文书
python基础之while循环语句的使用
2021/04/20 Python
详解 TypeScript 枚举类型
2021/11/02 Javascript