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 Web开发框架Django
Jun 30 Python
pyqt5简介及安装方法介绍
Jan 31 Python
获取python文件扩展名和文件名方法
Feb 02 Python
在Pycharm中修改文件默认打开方式的方法
Jan 17 Python
用Python徒手撸一个股票回测框架搭建【推荐】
Aug 05 Python
PyQt+socket实现远程操作服务器的方法示例
Aug 22 Python
python实现两个字典合并,两个list合并
Dec 02 Python
python如何通过twisted搭建socket服务
Feb 03 Python
python函数定义和调用过程详解
Feb 09 Python
Python3 读取Word文件方式
Feb 13 Python
python 引用传递和值传递详解(实参,形参)
Jun 05 Python
python+pyhyper实现识别图片中的车牌号思路详解
Dec 24 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
jQuery EasyUI API 中文文档 - ComboGrid 组合表格
2011/10/13 Javascript
原生js实现半透明遮罩层效果具体代码
2013/06/06 Javascript
JS实现同时搜索百度和必应的方法
2015/01/27 Javascript
js实现鼠标滚轮控制图片缩放效果的方法
2015/02/20 Javascript
javascript基础知识
2016/06/07 Javascript
jQuery的Each比JS原生for循环性能慢很多的原因
2016/07/05 Javascript
详解nodejs模板引擎制作
2017/06/14 NodeJs
jQuery实现碰到边缘反弹的动画效果
2018/02/24 jQuery
vue的keep-alive用法技巧
2019/08/15 Javascript
详解vue 自定义组件使用v-model 及探究其中原理
2019/10/11 Javascript
微信小程序利用button控制条件标签的变量问题
2020/03/15 Javascript
浅析TypeScript 命名空间
2020/03/19 Javascript
基于vue实现简易打地鼠游戏
2020/08/21 Javascript
Python实现的监测服务器硬盘使用率脚本分享
2014/11/07 Python
在windows下使用python进行串口通讯的方法
2019/07/02 Python
python项目对接钉钉SDK的实现
2019/07/15 Python
使用Python进行中文繁简转换的实现代码
2019/10/18 Python
基于python操作ES实例详解
2019/11/16 Python
Python函数的默认参数设计示例详解
2019/12/01 Python
python 实现查询Neo4j多节点的多层关系
2019/12/23 Python
Python实现投影法分割图像示例(二)
2020/01/17 Python
稀有和绝版书籍:Biblio.com
2017/02/02 全球购物
Johnston & Murphy官网: 约翰斯顿·墨菲牛津总统鞋
2018/01/09 全球购物
小米俄罗斯授权商店:Xiaomi俄罗斯
2019/12/08 全球购物
英国豪华家具和家居用品购物网站:Teddy Beau
2020/10/12 全球购物
抽象类和接口的区别
2012/09/19 面试题
创业计划书——互联网商机
2014/01/12 职场文书
乔迁之喜主持词
2014/03/27 职场文书
委托书范文
2014/04/02 职场文书
《鸟岛》教学反思
2014/04/26 职场文书
师范生求职信
2014/06/14 职场文书
学生党员一帮一活动总结
2014/07/08 职场文书
学用政策心得体会
2014/09/10 职场文书
民主评议党员自我鉴定
2014/10/21 职场文书
话题作文之成长
2019/12/09 职场文书
Redis主从配置和底层实现原理解析(实战记录)
2021/06/30 Redis