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 相关文章推荐
Python随机生成一个6位的验证码代码分享
Mar 24 Python
Python读写unicode文件的方法
Jul 10 Python
深入剖析Python的爬虫框架Scrapy的结构与运作流程
Jan 20 Python
由浅入深讲解python中的yield与generator
Apr 05 Python
Python爬取附近餐馆信息代码示例
Dec 09 Python
Python实现感知器模型、两层神经网络
Dec 19 Python
Java及python正则表达式详解
Dec 27 Python
Python基于FTP模块实现ftp文件上传操作示例
Apr 23 Python
python实现梯度下降算法
Mar 24 Python
Python远程视频监控程序的实例代码
May 05 Python
Python爬取爱奇艺电影信息代码实例
Nov 26 Python
在 Golang 中实现 Cache::remember 方法详解
Mar 30 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 八种基本的数据类型小结
2011/06/01 PHP
递归实现php数组转xml的代码分享
2015/05/14 PHP
wampserver改变默认网站目录的办法
2015/08/05 PHP
php+Memcached实现简单留言板功能示例
2017/02/15 PHP
ThinkPHP开发--使用七牛云储存
2017/09/14 PHP
JavaScript下申明对象的几种方法小结
2008/10/02 Javascript
javascript各浏览器中option元素的表现差异
2011/04/07 Javascript
基于jQuery实现的当离开页面时出现提示的实现代码
2011/06/27 Javascript
JQuery UI的拖拽功能实现方法小结
2012/03/14 Javascript
JS实现漂亮的窗口拖拽效果(可改变大小、最大化、最小化、关闭)
2015/10/10 Javascript
jQuery简单动画变换效果实例分析
2016/07/04 Javascript
JavaScript通过filereader接口读取文件
2017/05/10 Javascript
PHP7新特性简述
2017/06/11 Javascript
详解vue 配合vue-resource调用接口获取数据
2017/06/22 Javascript
ES6 系列之 WeakMap的使用示例
2018/08/06 Javascript
vue2使用keep-alive缓存多层列表页的方法
2018/09/21 Javascript
微信小程序实现跑马灯效果
2020/10/21 Javascript
微信小程序实现页面浮动导航
2019/01/28 Javascript
js时间转换毫秒的实例代码
2019/08/21 Javascript
Django admin美化插件suit使用示例
2017/12/12 Python
Python中dict和set的用法讲解
2019/03/28 Python
Python爬虫JSON及JSONPath运行原理详解
2020/06/04 Python
如何在pycharm中安装第三方包
2020/10/27 Python
css3实现3D文本悬停改变效果的示例代码
2019/01/16 HTML / CSS
HTML如何让IMG自动适应DIV容器大小的实现方法
2020/02/25 HTML / CSS
Speedo速比涛德国官方网站:世界领先的泳装品牌
2019/08/26 全球购物
在C中是否有模拟继承等面向对象程序设计特性的好方法
2012/05/22 面试题
20岁生日感言
2014/01/13 职场文书
捐资助学倡议书
2014/04/15 职场文书
竞选班干部演讲稿100字
2014/08/20 职场文书
2014公司党员自我评价范文
2014/09/11 职场文书
医德医风自我评价
2014/09/19 职场文书
学校清洁工岗位职责
2015/04/15 职场文书
教师理论学习心得体会
2016/01/21 职场文书
详解nodejs内置模块
2021/05/06 NodeJs
详解JavaScript中Arguments对象用途
2021/08/30 Javascript