python Django模板的使用方法(图文)


Posted in Python onNovember 04, 2013

模版基本介绍
模板是一个文本,用于分离文档的表现形式和内容。 模板定义了占位符以及各种用于规范文档该如何显示的各部分基本逻辑(模板标签)。 模板通常用于产生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 相关文章推荐
SublimeText 2编译python出错的解决方法(The system cannot find the file specified)
Nov 27 Python
完美解决Python matplotlib绘图时汉字显示不正常的问题
Jan 29 Python
python批量修改文件夹及其子文件夹下的文件内容
Mar 15 Python
Python应用领域和就业形势分析总结
May 14 Python
Python 函数list&amp;read&amp;seek详解
Aug 28 Python
Python利用matplotlib绘制约数个数统计图示例
Nov 26 Python
python已协程方式处理任务实现过程
Dec 27 Python
python nohup 实现远程运行不宕机操作
Apr 16 Python
Python基于pandas爬取网页表格数据
May 11 Python
经验丰富程序员才知道的8种高级Python技巧
Jul 27 Python
Django2.1.7 查询数据返回json格式的实现
Dec 29 Python
解决numpy和torch数据类型转化的问题
May 23 Python
使用python Django做网页
Nov 04 #Python
教你安装python Django(图文)
Nov 04 #Python
python条件和循环的使用方法
Nov 01 #Python
讲解python参数和作用域的使用
Nov 01 #Python
python列表与元组详解实例
Nov 01 #Python
python创建和使用字典实例详解
Nov 01 #Python
python分割和拼接字符串
Nov 01 #Python
You might like
PHP isset()与empty()的使用区别详解
2010/08/29 PHP
浅谈php+phpStorm+xdebug配置方法
2015/09/17 PHP
Yii框架扩展CGridView增加导出CSV功能的方法
2017/05/24 PHP
jquery $.getJSON()跨域请求
2011/12/21 Javascript
JS获取当前日期和时间的简单实例
2013/11/19 Javascript
ie9 提示'console' 未定义问题的解决方法
2014/03/20 Javascript
node.js应用后台守护进程管理器Forever安装和使用实例
2014/06/01 Javascript
js 数组去重的四种实用方法
2014/09/09 Javascript
javascript实现网站加入收藏功能
2015/12/16 Javascript
Bootstrap modal 多弹窗之叠加显示不出弹窗问题的解决方案
2017/02/23 Javascript
js实现百度登录框鼠标拖拽效果
2017/03/07 Javascript
vue2.0实现倒计时的插件(时间戳 刷新 跳转 都不影响)
2017/03/30 Javascript
微信小程序 实现点击添加移除class
2017/06/12 Javascript
使用npm安装最新版本nodejs
2018/01/18 NodeJs
Vue 页面跳转不用router-link的实现代码
2018/04/12 Javascript
vue 中滚动条始终定位在底部的方法
2018/09/03 Javascript
js实现扫雷源代码
2020/11/27 Javascript
如何在vue中使用kindeditor富文本编辑器
2020/12/19 Vue.js
Vue使用鼠标在Canvas上绘制矩形
2020/12/24 Vue.js
[27:39]Ti4 循环赛第二日 LGD vs Fnatic
2014/07/11 DOTA
[01:04:49]KG vs LGD 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/16 DOTA
Python实现过滤单个Android程序日志脚本分享
2015/01/16 Python
使用Eclipse如何开发python脚本
2018/04/11 Python
Python函数式编程指南:对生成器全面讲解
2019/11/19 Python
From CSV to SQLite3 by python 导入csv到sqlite实例
2020/02/14 Python
Pytorch中.new()的作用详解
2020/02/18 Python
24个canvas基础知识小结
2014/12/17 HTML / CSS
欧洲领先的电子和电信零售商和服务提供商:Currys PC World Business
2017/12/05 全球购物
一道Delphi面试题
2016/10/28 面试题
办公室内勤岗位职责范本
2013/12/09 职场文书
搞笑获奖感言
2014/01/30 职场文书
马丁路德金演讲稿
2014/05/19 职场文书
党员违纪检讨书怎么写
2014/11/01 职场文书
大学生见习报告范文
2014/11/03 职场文书
党员个人自我评价
2015/03/03 职场文书
汽车4S店销售经理岗位职责
2015/04/02 职场文书