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实现各进制转换的总结大全
Jun 18 Python
python SMTP实现发送带附件电子邮件
May 22 Python
Django实现表单验证
Sep 08 Python
django的分页器Paginator 从django中导入类
Jul 25 Python
Python中的 sort 和 sorted的用法与区别
Aug 10 Python
python图像处理模块Pillow的学习详解
Oct 09 Python
Python中base64与xml取值结合问题
Dec 22 Python
python多线程实现代码(模拟银行服务操作流程)
Jan 13 Python
python数据库开发之MongoDB安装及Python3操作MongoDB数据库详细方法与实例
Mar 18 Python
Python pickle模块常用方法代码实例
Oct 10 Python
python 实现aes256加密
Nov 27 Python
Python使用Beautiful Soup(BS4)库解析HTML和XML
Jun 05 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 UTF8 文件的签名问题
2009/10/30 PHP
一个简洁的PHP可逆加密函数(分享)
2013/06/06 PHP
PHP中常用的数组操作方法笔记整理
2016/05/16 PHP
js列举css中所有图标的实现代码
2011/07/04 Javascript
firefox下jquery iframe刷新页面提示会导致重复之前动作
2012/12/17 Javascript
jquery属性过滤选择器使用示例
2013/06/18 Javascript
四种参数传递的形式——URL,超链接,js,form表单
2015/07/24 Javascript
跟我学习javascript的定时器
2015/11/19 Javascript
分享javascript实现的冒泡排序代码并优化
2016/06/05 Javascript
一道优雅面试题分析js中fn()和return fn()的区别
2016/07/05 Javascript
vue 组件 全局注册和局部注册的实现
2018/02/28 Javascript
使用vue-cli webpack 快速搭建项目的代码
2018/11/21 Javascript
原生js实现二级联动菜单
2019/11/27 Javascript
python分割列表(list)的方法示例
2017/05/07 Python
python flask实现分页效果
2017/06/27 Python
酷! 程序员用Python带你玩转冲顶大会
2018/01/17 Python
Python实现接受任意个数参数的函数方法
2018/04/21 Python
Python使用cx_Oracle模块操作Oracle数据库详解
2018/05/07 Python
Python实现统计给定字符串中重复模式最高子串功能示例
2018/05/16 Python
Python datetime包函数简单介绍
2019/08/28 Python
python 队列基本定义与使用方法【初始化、赋值、判断等】
2019/10/24 Python
Python批量启动多线程代码实例
2020/02/18 Python
python 实现简易的记事本
2020/11/30 Python
python中reload重载实例用法
2020/12/15 Python
Lululemon加拿大官网:加拿大知名体育服装零售商
2019/04/12 全球购物
Vivo俄罗斯官方在线商店:中国智能手机品牌
2019/10/04 全球购物
MAC彩妆澳洲官网:M·A·C AU
2021/01/17 全球购物
易程科技软件测试笔试
2013/03/24 面试题
物流专业大学生职业生涯规划书范文
2014/01/15 职场文书
光盘行动倡议书
2014/02/02 职场文书
市场营销战略计划书
2014/05/06 职场文书
小学英语教师先进事迹
2014/05/28 职场文书
初中班级口号
2014/06/09 职场文书
食品安全责任书范本
2015/05/09 职场文书
Mysql数据库命令大全
2021/05/26 MySQL
PyTorch device与cuda.device用法
2022/04/03 Python