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使用装饰器和线程限制函数执行时间的方法
Apr 18 Python
快速入门python学习笔记
Dec 06 Python
Python编程产生非均匀随机数的几种方法代码分享
Dec 13 Python
简单实现python数独游戏
Mar 30 Python
Python实现的生产者、消费者问题完整实例
May 30 Python
使用Python对微信好友进行数据分析
Jun 27 Python
Python使用pyserial进行串口通信的实例
Jul 02 Python
Django基础三之视图函数的使用方法
Jul 18 Python
Python PyQt5模块实现窗口GUI界面代码实例
May 12 Python
关于PyCharm安装后修改路径名称使其可重新打开的问题
Oct 20 Python
Python3 使用pip安装git并获取Yahoo金融数据的操作
Apr 08 Python
Python使用Beautiful Soup(BS4)库解析HTML和XML
Jun 05 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 park、unpark、ord 函数使用方法(二进制流接口应用实例)
2010/10/19 PHP
PHP多个版本的分析解释
2011/07/21 PHP
php数据结构与算法(PHP描述) 查找与二分法查找
2012/06/21 PHP
比较strtr, str_replace和preg_replace三个函数的效率
2013/06/26 PHP
基于PHP代码实现中奖概率算法可用于刮刮卡、大转盘等抽奖算法
2015/12/20 PHP
PHP按指定键值对二维数组进行排序的方法
2015/12/22 PHP
深入浅析安装PhpStorm并激活的步骤详解
2020/09/17 PHP
宝塔面板在NGINX环境中TP5.1如何运行?
2021/03/09 PHP
你可能不再需要JQUERY
2021/03/09 Javascript
a标签的css样式四个状态
2021/03/09 HTML / CSS
checkbox 复选框不能为空
2009/07/11 Javascript
JQuery zClip插件实现复制页面内容到剪贴板
2015/11/02 Javascript
AngularJS应用开发思维之依赖注入3
2016/08/19 Javascript
JS获取中文拼音首字母并通过拼音首字母快速查找页面内对应中文内容的方法【附demo源码】
2016/08/19 Javascript
JS简单测试循环运行时间的方法
2016/09/04 Javascript
Vue.js每天必学之方法与事件处理器
2016/09/06 Javascript
ionic2 tabs 图标自定义实例
2017/03/08 Javascript
基于vue.js实现的分页
2018/03/13 Javascript
详解mpvue小程序中怎么引入iconfont字体图标
2018/10/01 Javascript
react配置antd按需加载的使用
2019/02/11 Javascript
js笔试题-接收get请求参数
2019/06/15 Javascript
在 Vue 中编写 SVG 图标组件的方法
2020/02/24 Javascript
从零学python系列之数据处理编程实例(一)
2014/05/22 Python
使用 Python 获取 Linux 系统信息的代码
2014/07/13 Python
Python、PyCharm安装及使用方法(Mac版)详解
2017/04/28 Python
Python求离散序列导数的示例
2019/07/10 Python
Python英文文章词频统计(14份剑桥真题词频统计)
2019/10/13 Python
浅析python字符串前加r、f、u、l 的区别
2021/01/24 Python
使用phonegap克隆和删除联系人的实现方法
2017/03/31 HTML / CSS
财务与信息服务专业推荐信
2013/11/28 职场文书
全国优秀辅导员事迹材料
2014/05/14 职场文书
机票销售员态度不好检讨书
2014/09/27 职场文书
2014年前台个人工作总结
2014/11/14 职场文书
大学生安全教育主题班会
2015/08/12 职场文书
Django使用echarts进行可视化展示的实践
2021/06/10 Python
Python爬取奶茶店数据分析哪家最好喝以及性价比
2022/09/23 Python