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去掉字符串中空格的方法
Mar 11 Python
Python实现基于权重的随机数2种方法
Apr 28 Python
详解python的sorted函数对字典按key排序和按value排序
Aug 10 Python
pycharm 配置远程解释器的方法
Oct 28 Python
python无限生成不重复(字母,数字,字符)组合的方法
Dec 04 Python
python实时获取外部程序输出结果的方法
Jan 12 Python
解决pymysql cursor.fetchall() 获取不到数据的问题
May 15 Python
Python 跨.py文件调用自定义函数说明
Jun 01 Python
Python如何发送与接收大型数组
Aug 07 Python
Django如何继承AbstractUser扩展字段
Nov 27 Python
python3 googletrans超时报错问题及翻译工具优化方案 附源码
Dec 23 Python
python基于tkinter制作下班倒计时工具
Apr 28 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访问查询mysql数据的三种方法
2006/10/09 PHP
Yii把CGridView文本框换成下拉框的方法
2014/12/03 PHP
laravel框架语言包拓展实现方法分析
2019/11/22 PHP
Span元素的width属性无效果原因及解决方案
2010/01/15 Javascript
js防止页面被iframe调用的方法
2014/10/30 Javascript
Javascript限制网页只能在微信内置浏览器中访问
2014/11/09 Javascript
jquery与ajax获取特殊字符实例详解
2017/01/08 Javascript
js处理层级数据结构的方法小结
2017/01/17 Javascript
如何通过非数字与字符的方式实现PHP WebShell详解
2017/07/02 Javascript
Vue与Node.js通过socket.io通信的示例代码
2018/07/25 Javascript
如何使用electron-builder及electron-updater给项目配置自动更新
2018/12/24 Javascript
如何写好一个vue组件,老夫的一年经验全在这了(推荐)
2019/05/18 Javascript
[01:28:31]《加油DOTA》真人秀 第五期
2014/09/01 DOTA
Python实现线程池代码分享
2015/06/21 Python
开始着手第一个Django项目
2015/07/15 Python
Python中文件I/O高效操作处理的技巧分享
2017/02/04 Python
利用标准库fractions模块让Python支持分数类型的方法详解
2017/08/11 Python
python实现机械分词之逆向最大匹配算法代码示例
2017/12/13 Python
Python批量合并有合并单元格的Excel文件详解
2018/04/05 Python
使用python的pandas为你的股票绘制趋势图
2019/06/26 Python
巴西最大的家电和百货零售商:Casas Bahia
2016/11/22 全球购物
西班牙在线宠物商店:zooplus.es
2017/02/24 全球购物
佳能加拿大网上商店:Canon eStore Canada
2018/04/04 全球购物
Book Depository亚太地区:一家领先的国际图书零售商
2019/05/05 全球购物
Luxplus荷兰:以会员价购买美容产品等,独家优惠
2019/08/30 全球购物
英国折扣高尔夫商店:Discount Golf Store
2019/11/19 全球购物
一道写SQL的面试题和答案
2013/11/19 面试题
介绍一下如何优化MySql
2016/12/20 面试题
村庄环境整治方案
2014/05/15 职场文书
安全生产年活动总结
2014/08/29 职场文书
2015年幼师工作总结
2015/04/28 职场文书
博士论文答辩开场白
2015/06/01 职场文书
2016读书月活动心得体会
2016/01/14 职场文书
nginx 防盗链防爬虫配置详解
2021/03/31 Servers
光之国的四大叛徒:第一贝利亚导致宇宙毁灭,赛文奥特曼在榜
2022/03/18 日漫
Python代码实现双链表
2022/05/25 Python