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 18 Python
python3+PyQt5+Qt Designer实现堆叠窗口部件
Apr 20 Python
opencv python统计及绘制直方图的方法
Jan 21 Python
python+pyqt5实现24点小游戏
Jan 24 Python
简单了解python的一些位运算技巧
Jul 13 Python
windows 10 设定计划任务自动执行 python 脚本的方法
Sep 11 Python
python Popen 获取输出,等待运行完成示例
Dec 30 Python
python词云库wordCloud使用方法详解(解决中文乱码)
Feb 17 Python
python GUI库图形界面开发之PyQt5线程类QThread详细使用方法
Feb 26 Python
Selenium启动Chrome时配置选项详解
Mar 18 Python
Python BeautifulReport可视化报告代码实例
Apr 13 Python
Django操作cookie的实现
May 26 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 GD库生成图像的几个函数总结
2014/11/19 PHP
php实现smarty模板无限极分类的方法
2015/12/07 PHP
php mysql_list_dbs()函数用法示例
2017/03/29 PHP
前后台交互过程中json格式如何解析以及如何生成
2012/12/26 Javascript
js原生appendChild的bug解决心得分享
2013/07/01 Javascript
js使用递归解析xml
2014/12/12 Javascript
浅谈EasyUI中编辑treegrid的方法
2015/03/01 Javascript
js实现浏览本地文件并显示扩展名的方法
2015/08/17 Javascript
jQuery中常用的遍历函数用法实例总结
2015/09/01 Javascript
简单谈谈Javascript中类型的判断
2015/10/19 Javascript
JQuery ztree 异步加载实例讲解
2016/02/25 Javascript
React.js入门实例教程之创建hello world 的5种方式
2016/05/11 Javascript
微信小程序 定位到当前城市实现实例代码
2017/02/23 Javascript
Vue.js之slot深度复制详解
2017/03/10 Javascript
JavaScript实现移动端轮播效果
2017/06/06 Javascript
Angular5给组件本身的标签添加样式class的方法
2018/04/07 Javascript
MVVM 双向绑定的实现代码
2018/06/21 Javascript
webpack多入口多出口的实现方法
2018/08/17 Javascript
解决angular2在双向数据绑定时[(ngModel)]无法使用的问题
2018/09/13 Javascript
vue2过滤器模糊查询方法
2018/09/16 Javascript
jQuery实现雪花飘落效果
2020/08/02 jQuery
在win10和linux上分别安装Python虚拟环境的方法步骤
2019/05/09 Python
python实现把二维列表变为一维列表的方法分析
2019/10/08 Python
基于Python实现扑克牌面试题
2019/12/11 Python
Python unittest工作原理和使用过程解析
2020/02/24 Python
Python socket连接中的粘包、精确传输问题实例分析
2020/03/24 Python
马来西亚在线购物:POPLOOK.com
2019/12/09 全球购物
南京某公司笔试题
2013/01/27 面试题
软件测试笔试题
2012/10/25 面试题
初中班主任寄语
2014/04/04 职场文书
10的分与合教学反思
2014/04/30 职场文书
励志演讲稿大全
2014/08/21 职场文书
离婚协议书应该怎么写
2014/10/12 职场文书
小学毕业教师寄语
2019/06/21 职场文书
pandas 操作 Excel操作总结
2021/03/31 Python
Vue3.0 手写放大镜效果
2021/07/25 Vue.js