在本章中,我们开始模板,在前面的章节,您可能已经注意到,我们回到文本的方式有点特别的示例视图。

那。HTML直接在硬编码 Python 其中代码。

这的确是一个小BT。

def current_datetime(request):
now = datetime.datetime.now()
html = "<html><body>It is now %s.</body></html>" % now
return HttpResponse(html)

假设我们学习了模板。就不会在这样BT了,再Django中模板事实上就是一个html文件。我先来看一个简单的样例:

<html>
<head><title>订单</title></head> <body> <h1>订单</h1> <p>尊敬的 {{ person_name }},</p> <p>感谢来您订购的来自 {{ company }} 的订单. 订单时间为: {{ ship_date|date:"F j, Y" }}.</p> <p>这里是您的订货列表:</p> <ul>
{% for item in item_list %}
<li>{{ item }}</li>
{% endfor %}
</ul> {% if ordered_warranty %}
<p>您的保修信息将包括在包裹中。 </p>
{% else %}
<p>你没有定购保修要求, 所以,假设机器停止执行您将自己负责。</p>
{% endif %} <p>张三,<br />{{ company }}</p> </body>
</html>

用两个大括号括起来的文字(比如 {{ person_name }} )称为 变量(variable) 。这意味着在此处插入指定变量的值。





    被大括号和百分号包围的文本(比如 {% if ordered_warranty %} )是 模板标签(template tag) 。标签(tag)定义比較明白。即: 仅通知模板系统完毕某些工作的标签。

事实上就是写代码和语句的地方。





    这个模板的第二段中有一个关于filter过滤器的样例,它是一种最便捷的转换变量输出格式的方式。

如这个样例中的{{ship_date|date:”F j, Y” }},我们将变量ship_date传递给date过滤器。同一时候指定參数”F j,Y”。date过滤器依据參数进行格式输出。 过滤器是用管道符(|)来调用的。详细能够參见Unix管道符。

事实上这里我更喜欢在后台过滤这些信息。由于我们不能要求美工或者參与布局设计的人员有太多编程的基础。所以教程里面关于模版的介绍临时能够忽略了。





    了解了模板,我们如今就来创建一个模板,以及看看在视图中是怎样应用的。以下我们先创建一个名为template的目录,这个目录里面将会放入我们编辑的模板,就是html文件。

然后我们须要在setting.py这个文件里找到“TEMPLATE_DIRS =”,然后告诉 Django 的模板载入机制在哪里查找模板。

选择一个目录用于存放模板并将其加入到TEMPLATE_DIRS 中:

TEMPLATE_DIRS = ("Bidding/templates"

)

事实上这里的文件夹以及路径能够自己制定,仅仅须要在setting里面设置一下就ok了,这里也能够使用绝对路径如 :

TEMPLATE_DIRS = (
'C:/www/django/templates',
)

完毕 TEMPLATE_DIRS 设置后,下一步就是改动视图代码,让它使用 Django 模板载入功能而不是对模板路径硬编码。

返回 current_datetime 视图,进行例如以下改动:

from django.shortcuts import render_to_response
import datetime def current_datetime(request):
now = datetime.datetime.now()
return render_to_response('current_datetime.html', {'current_date': now})

我们不再须要导入 get_template 、 Template 、 Context 和 HttpResponse 。

相反,我们导入 django.shortcuts.render_to_response 。

import datetime 继续保留。

    

    在 current_datetime 函数中。我们仍然进行 now 计算。但模板载入、上下文创建、模板解析和 HttpResponse 创建工作均在对 render_to_response() 的调用中完毕了。 因为 render_to_response() 返回 HttpResponse 对象,因此我们仅需在视图中 return 该值。





    render_to_response() 的第一个參数必须是要使用的模板名称。

假设要给定第二个參数,那么该參数必须是为该模板创建 Context 时所使用的字典。 假设不提供第二个參数。 render_to_response() 使用一个空字典。

这里面的 {'current_date': now} 须要说明一下:now为在视图里面的变量。而current_date 则是模板中的变量。事实上假设这两个变量一直的话。我们能够简化写成这样:

from django.shortcuts import render_to_response
import datetime def current_datetime(request):
current_date = datetime.datetime.now()
return render_to_response('current_datetime.html', locals())

把全部的模板都存放在一个文件夹下可能会让事情变得难以掌控。

你可能会考虑把模板存放在你模板文件夹的子文件夹中。这很好。

也能够这样:

return render_to_response('dateapp/current_datetime.html', locals())

Windows用户必须使用斜杠而不是反斜杠。说了这么多。我想你一定和我一样想试试这个模板了。上面已经介绍了views.py的改动内容。以下我们来创建一个模板current_datetime.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>显示当前时间</title>
</head>
<body>
<h1>这不过一个简单的样例</h1>
<hr>
<p>当前时间为:{{ current_date }}</p>
</body>
</html>

然后我们把current_datetime.html文件放入templates。

在这之前确保一下几个步骤已经完毕

1.改动了setting中的TEMPLATE_DIRS = ("Bidding/templates")

2.改动了views.py

from django.shortcuts import render_to_response
import datetime def current_datetime(request):
current_date = datetime.datetime.now()
return render_to_response('current_datetime.html', locals())

然后上传代码,看效果把。

以下我们来看看include 模板标签,就是模板里面能够套模板,首先我们在template文件夹里面再创建一个base的文件夹,在这里文件夹里面我们准备放上网页的top和bottom的模板。

top.html:

<div style="background:#eeeeee;width:100%;height:60px;">
学习python是个快乐的过程----{{ author }}
</div>

bottom.html:

<div style="background:#eeeeee;width:100%;height:30px;">
版权全部----{{ author }}
</div>

然后我们再建立一个新的模板,把他放在template根文件夹里面,命名为template_include.html

template_include.html:

<html>
<body>
{% include "base/top.html" %}
<h1>再过 {{ offset }} 个小时, 时间将会是 {{ dt }}.</h1>
{% include "base/bottom.html" %}
</body>
</html>

然后我们在改动一下之前的 hours_ahead 视图:

def hours_ahead(request, offset):
try:
offset = int(offset)
except ValueError:
raise Http404()
dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
author="hemeng80"
return render_to_response('template_include.html', locals())

到眼下为止,我们的模板范例都仅仅是些零星的 HTML 片段,但在实际应用中,你将用 Django 模板系统来创建整个 HTML 页面。

这就带来一个常见的 Web 开发问题: 在整个站点中。怎样降低共用页面区域(比方站点导航)所引起的反复和冗余代码?





    解决该问题的传统做法是使用 server端的 includes 。你能够在 HTML 页面中使用该指令将一个网页嵌入到还有一个中。 其实, Django 通过刚才讲述的 {% include %} 支持了这样的方法。

可是用 Django 解决此类问题的首选方法是使用更加优雅的策略—— 模板继承 。





     首先我们建立一个基类模板命名为 base.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<h1>这里是一个学习用的測试站点</h1>
{% block content %}{% endblock %}
{% block footer %}
<hr>
<p>感谢你的訪问</p>
{% endblock %}
</body>
</html>

如今我们已经有了一个基本模板。我们能够在建立一个 hello_base.html 模板来 使用它:

{% extends "base.html" %}

{% block title %}欢迎{% endblock %}

{% block content %}
<p>这时我的第一个Python程序: {{ MyString }}.</p>
{% endblock %}

在改造一下views.py:

# -*- coding: utf-8 -*-
from django.http import HttpResponse
from django.shortcuts import render_to_response
import datetime def hello(request):
return HttpResponse('Hello world') def current_datetime(request):
current_date = datetime.datetime.now()
return render_to_response('current_datetime.html', locals()) def hours_ahead(request, offset):
try:
offset = int(offset)
except ValueError:
raise Http404()
dt = datetime.datetime.now() + datetime.timedelta(hours=offset)
author="hemeng80"
return render_to_response('template_include.html', locals()) def hello_base(request):
MyString = 'Hello world'
return render_to_response('hello_base.html', locals())

在配置下urls.py:

from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover() urlpatterns = patterns('',
# Examples:
# url(r'^$', 'Bidding.views.home', name='home'),
# url(r'^Bidding/', include('Bidding.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'^hello/$', 'Bidding.views.hello'),
url(r'^time/$', 'Bidding.views.current_datetime'),
url(r'^time/plus/(\d{1,2})/$', 'Bidding.views.hours_ahead'),
url(r'^hello_base/$', 'Bidding.views.hello_base'),
)

在看看程序的执行结果,你一定能够了解模板的包括、继承的意义了。

版权声明:本文博客原创文章,博客,未经同意,不得转载。

Python+Django+SAE系列教程10-----Django模板的更多相关文章

  1. Python+Django+SAE系列教程17-----authauth (认证与授权)系统1

    通过session,我们能够在多次浏览器请求中保持数据,接下来的部分就是用session来处理用户登录了. 当然,不能仅凭用户的一面之词,我们就相信,所以我们须要认证. 当然了,Django 也提供了 ...

  2. Python+Django+SAE系列教程11-----request/pose/get/表单

    表单request,post,get 首先我们来看看Request对象,在这个对象中包括了一些实用的信息,学过B/S开发的人来说这并不陌生,我们来看看在Django中是怎样实现的: 属性/方法 说明 ...

  3. Python+Django+SAE系列教程9-----Django的视图和URL

    第三.四.五章介绍的就是Django中MVC的视图.模板.模型了. 首先来看视图(view),在用Django生成的站点目录中,创建一个view.py文件,这个文件開始是空的.然后我们输入下面内容: ...

  4. Python+Django+SAE系列教程13-----MySQL记录的添\删\改

    建立了数据库后,我们就来做一个简单的表(person_classroom)的加入.删除.改动的操作. 首先我们建立一个加入的页面的模板Classroom_Add.html(加入的表单)并把它放在Bid ...

  5. Python+Django+SAE系列教程6-----本地配置Django

    前五章.我们介绍了Python的语法,本章開始介绍Django. Python的Web框架有非常多,有Django.web2py.tornado.web.py等.我们这里选 则Django.至于这些框 ...

  6. Python+Django+SAE系列教程15-----输出非HTML内容(图片/PDF)

    一个Django视图函数 必须 接受一个HttpRequest 实例作为它的第一个參数 返回一个HttpResponse 实例 从一个视图返回一个非HTML 内容的关键是在构造一个 HttpRespo ...

  7. Python+Django+SAE系列教程12-----配置MySQL数据库

    由于SAE上支持的是Mysql,首先我们要在本地配置一个Mysql的环境 ,我在网上找到MySQL-python-1.2.4b4.win32-py2.7.exe,并双击 安装 选择典型安装 安装结束后 ...

  8. Python+Django+SAE系列教程16-----cookie&amp;session

    本章我们来解说cookie和session ,这两个东西相信大家一定不陌生,概念就不多讲了,我们直接来看其使用方法,首先是cookie,我们在view中加入三个视图,一个是显示cookie的,一个是设 ...

  9. Python+Django+SAE系列教程14-----使表单更安全

    还记得我们上一章提到过的加入页面吗? watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvaGVtZW5nMTk4MA==/font/5a6L5L2T/fonts ...

随机推荐

  1. [Recompose] Add Lifecycle Hooks to a Functional Stateless Component using Recompose

    Learn how to use the 'lifecycle' higher-order component to conveniently use hooks without using a cl ...

  2. [CSS] Build Responsive CSS Layouts with Tachyons

    Building responsive css layouts is critical in any modern website. Tachyons makes this easy by desig ...

  3. php实现求一个数的质数因子

    php实现求一个数的质数因子 一.总结 一句话总结:这么简单的题目,还是把变量定义的位置和自增的位置写错. 1 <?php 2 $num=trim(fgets(STDIN)); 3 //如果$n ...

  4. Photoshop怎么实现图片局部马赛克

    学好ps是一件很重要的事情,作为日常必备技能,不管是在遇到这样的同时请求帮忙或者老板发配的任务的时候,就能分分钟派上用场了. 1:安装运行photoshop,点击文件-打开,选择要ps的图片. 图片. ...

  5. Tokumx vs Mongodb

    Mongodb是一个文档型nosql数据库 採用C++编写 Mongo DB最大的优势在于全部的数据持久操作都无需开发者手动编写SQL语句,直接调用方法就能够轻松的实现CRUD操作. 非常多人觉得mo ...

  6. kindeditor4跨域上传图片解决

    项目中正在使用kindeditor, 版本号4.1.10 非常多公司的图片会走CDN,须要单独的一台图片上传服务如:(upload.268xue.com) kindeditor上传图片的简单内部流程: ...

  7. 树莓派——root用户和sudo

    Linux操作系统是一个多用户操作系统,它同意多个用户登录和使用一台计算机. 为了保护计算机(和其它用户的隐私).用户都被限制了能做的事情. 大多数用户都同意执行计算机上大部分程序,而且编辑和保存存放 ...

  8. 设置非ARC

    设置非ARC:   在build phase 设置中compile sources 选择非arc文件,设置键值为-fno-objc-arc

  9. NSstring封装

    来自http://devtang.com/blog/2012/02/14/nsstring-java-like-wrapper/ NSStringWrapper.h #import <Found ...

  10. Method for sub-pixel texture mapping and filtering

    BACKGROUND OF THE INVENTION 1. Field of the Invention The present invention relates to a method for ...