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通过select实现异步IO的方法
Jun 04 Python
详谈Python3 操作系统与路径 模块(os / os.path / pathlib)
Apr 26 Python
基于django channel实现websocket的聊天室的方法示例
Apr 11 Python
使用python快速在局域网内搭建http传输文件服务的方法
Nov 14 Python
Python warning警告出现的原因及忽略方法
Jan 31 Python
Django-imagekit的使用详解
Jul 06 Python
Python 整行读取文本方法并去掉readlines换行\n操作
Sep 03 Python
python PIL模块的基本使用
Sep 29 Python
详解基于python的全局与局部序列比对的实现(DNA)
Oct 07 Python
利用Opencv实现图片的油画特效实例
Feb 28 Python
Python办公自动化之Excel(中)
May 24 Python
Python连接Postgres/Mysql/Mongo数据库基本操作大全
Jun 29 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
中东人咖啡哲学
2021/03/03 咖啡文化
6种php上传图片重命名的方法实例
2013/11/04 PHP
php采集自中央气象台范围覆盖全国的天气预报代码实例
2015/01/04 PHP
PHP基于GD库的图像处理方法小结
2016/09/27 PHP
基于ThinkPHP5.0实现图片上传插件
2017/09/25 PHP
tp5递归 无限级分类详解
2019/10/18 PHP
javascript 基础篇4 window对象,DOM
2012/03/14 Javascript
JS对img进行操作(换图片/切图/轮换/停止)
2013/04/17 Javascript
js调用百度地图及调用百度地图的搜索功能
2015/09/07 Javascript
CSS或者JS实现鼠标悬停显示另一元素
2016/01/22 Javascript
让图片跳跃起来  javascript图片轮播特效
2016/02/16 Javascript
从零学习node.js之详解异步控制工具async(八)
2017/02/27 Javascript
angularjs中ng-bind-html的用法总结
2017/05/23 Javascript
js实现本地图片文件拖拽效果
2017/07/18 Javascript
微信小程序实现根据字母选择城市功能
2017/08/16 Javascript
vue对storejs获取的数据进行处理时遇到的几种问题小结
2018/03/20 Javascript
小程序tab页无法传递参数的方法
2018/08/03 Javascript
详解JavaScript中关于this指向的4种情况
2019/04/18 Javascript
JavaScript原生数组函数实例汇总
2020/10/14 Javascript
Python实现Linux命令xxd -i功能
2016/03/06 Python
Python使用迭代器打印螺旋矩阵的思路及代码示例
2016/07/02 Python
详解Python中表达式i += x与i = i + x是否等价
2017/02/08 Python
python和ruby,我选谁?
2017/09/13 Python
Python数据结构与算法之图的广度优先与深度优先搜索算法示例
2017/12/14 Python
Python实现迭代时使用索引的方法示例
2018/06/05 Python
python生成n个元素的全组合方法
2018/11/13 Python
python绘制雷达图实例讲解
2021/01/03 Python
世界上最大的网络主机公司:1&1
2016/10/12 全球购物
Carolina工作鞋官网:Carolina Footwear
2019/03/14 全球购物
解释一下Windows的消息机制
2014/01/30 面试题
yy司仪主持词
2014/03/22 职场文书
勤俭节约倡议书
2014/04/14 职场文书
小学生母亲节演讲稿
2014/05/07 职场文书
民族精神月活动总结
2014/08/28 职场文书
2015纪念九一八事变84周年演讲稿
2015/03/19 职场文书
申请吧主发表的感言
2015/08/03 职场文书