在例子视图中返回文本的方式有点特别,即HTML被直接硬编码在Python代码之中。css
def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html)
尽管这种技术便于解释视图是如何工做的,但直接将HTML硬编码到你的视图里却并是一个好主意。让咱们来看一下为何:html
基于这些缘由,将页面的设计和Python的代码分离开会更干净简洁更容易维护。咱们可使用Django的模板系统(Template System)来是如今这种模式,这就是本章要具体讨论的问题。python
Python的模板:HTML代码 + 模板语法程序员
def current_time(req): # ================================原始的视图函数 # import datetime # now=datetime.datetime.now() # html="<html><body>如今时刻:<h1>%s.</h1></body></html>" %now # ================================django模板修改的视图函数 # from django.template import Template,Context # now=datetime.datetime.now() # t=Template('<html><body>如今时刻是:<h1>{{current_date}}</h1></body></html>') # #t=get_template('current_datetime.html') # c=Context({'current_date':str(now)}) # html=t.render(c) # # return HttpResponse(html) #另外一种写法(推荐) import datetime now=datetime.datetime.now() return render(req, 'current_datetime.html', {'current_date':str(now)[:19]})
在Django模板中遍历复杂数据结构的关键是句点字符,语法:数据库
{{var_name}}
views.py:django
def index(request): import datetime s="hello" l=[111,222,333] # 列表 dic={"name":"yuan","age":18} # 字典 date = datetime.date(1993, 5, 2) # 日期对象 class Person(object): def __init__(self,name): self.name=name person_yuan=Person("yuan") # 自定义类对象 person_egon=Person("egon") person_alex=Person("alex") person_list=[person_yuan,person_egon,person_alex] return render(request,"index.html",{"l":l,"dic":dic,"date":date,"person_list":person_list})
template:缓存
<h4>{{s}}</h4> <h4>列表:{{ l.0 }}</h4> <h4>列表:{{ l.2 }}</h4> <h4>字典:{{ dic.name }}</h4> <h4>日期:{{ date.year }}</h4> <h4>类对象列表:{{ person_list.0.name }}</h4>
注:句点符也能够用来引用对象的方法(无参数方法):安全
<h4>字典:{{ dic.name.upper }}</h4>
语法:数据结构
{{obj|filter_name:param}}
defaultapp
若是一个变量是False后者为空,使用给定的默认值。不然,使用变量的值。例如:
{{ value|default:'nothing' }}
length
返回值的长度。它对字符串和列表都起做用。例如:
{{ value|length }}
若是value是['a', 'b', 'c', 'd']
,那么输出的就是4.
filesizeformat
将值格式化为一个 “人类可读的” 文件尺寸 (例如 '13 KB'
, '4.1 MB'
, '102 bytes'
, 等等)。例如:
{{ value|filesizeformat }}
若是value = 123456789,输出将会是117.7 MB。
date
若是value = datetime.datetime.now()
{{ value|date:"Y-m-d" }}
slice
若是value = "hello world"
{{ value|slice:"2:-1" }}
truncatechars
若是字符串字符多于指定的字符数量,那么会被截断。截断的字符串将以可翻译的省略号序列("...")结尾。
参数:要截断的字符数
{{ value|truncatechars:9 }}
safe
Django的模板中会对HTML标签和JS语法等标签进行自动转义,缘由显而易见这样是为了安全。可是有时候咱们可能不但愿这些HTML元素被转义,好比咱们作一个内容管理系统,后他添加的文章中是通过修饰的,这些修饰多是经过一个相似于FCKeditor编辑加注了HTML修饰符的文本,若是自动转义的话显示的就是保护HTML标签的源文件。为了在Django中关闭HTML的自动转义有两种方式,若是是一个单独的变量咱们能够经过过滤器"|safe"的方式告诉Django这段代码是安全的没必要转义。好比:
value = "<a href=''>点击</a>"
{{ value|safe }}
标签看起来像是这样:{% tag %}
。标签比变量更加复杂:一些在输出中建立文本,一些经过循环或逻辑来控制流程,一些加载其后的变量将使用到的额外信息的模板中。一些标签须要开开始和结束标签(例如{% tag %} ...标签 内容... {% endtag %}
)。
for标签
遍历每个元素:
能够利用{% for obj in list reversed %}
方向完成循环。
遍历一个字典:
{% for key,val in dic.items %} <p>{{ key }}:{{ val }}</p> {% endfor %}
注:循环序号能够经过{{ for|loop }}
显示
forloop.counter # The current iteration of the loop (1-indexed) forloop.counter0 # The current iteration of the loop (0-indexed) forloop.revcounter # The number of iterations from the end of the loop (1-indexed) forloop.revcounter0 # The number of iterations from the end of the loop (0-indexed) forloop.first # True if this is the first time through the loop forloop.last # True if this is the last time through the loop
for ... empty
for标签带有一个可选的{% empty %}
从句,以便在给出的组是空的或者没有被找到时,能够有所操做。
{% for person in person_list %} <p>{{ person.name }}</p> {% empty %} <p>sorry,no person here</p> {% endfor %}
if 标签
{% if %}
会对一个变量求值,若是它的值是True(存在、不为空、且不是boolean类型的False值),对应的内容块会输出。
{% if num > 100 or num < 0 %} <p>无效</p> {% elif num > 80 and num < 100 %} <p>优秀</p> {% else %} <p>凑活吧</p> {% endif %}
with 标签
使用一个简单地名字缓存一个复杂的变量,当你须要使用一个“昂贵”的方法(好比访问数据库)不少次的时候是很是有用的。例如:
{% with total=business.employees.count %} {{ total }} employee{{ total|pluralize }} {% endwith %}
csrf_token 标签
这个标签用于跨站请求伪造保护。
一、在settings中的INSTALLED_APPS配置当前app,否则Django没法找到自定义的simple_tag。
二、在app中建立templatetags模块(模块名只能是templatetags)。
三、建立任意 .py 文件,如:my_tags.py。
from django import template from django.utils.safestring import mark_safe register = template.Library() #register的名字是固定的,不可改变 @register.filter def filter_multi(v1,v2): return v1 * v2 @register.simple_tag def simple_tag_multi(v1,v2): return v1 * v2 @register.simple_tag def my_input(id,arg): result = "<input type='text' id='%s' class='%s' />" %(id,arg,) return mark_safe(result)
四、在使用自定义simple_tag和filter的HTML文件中导入以前建立的my_tags.py。
{% load my_tags %}
五、使用simple_tag和filter(如何调用)
-------------------------------.html {% load xxx %} # num=12 {{ num|filter_multi:2 }} #24 {{ num|filter_multi:"[22,333,4444]" }} {% simple_tag_multi 2 5 %} 参数不限,但不能放在if for语句中 {% simple_tag_multi num 5 %}
注:filter能够用在if等语句后,simpe_tag不能够。
{% if num|filter_multi:30 > 100 %} {{ num|filter_multi:30 }} {% endif %}
Django模板引擎中最强大也是最复杂的部分就是模板继承了。模板继承可让你建立一个基本的“骨架”模板,它包含你站点中的所有元素,而且能够定义可以被子模板覆盖的blocks.
经过从下面这个例子开始,能够容易地理解模板继承:
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style.css" /> <title>{% block title %}My amazing site{% endblock %}</title> </head> <body> <div id="sidebar"> {% block sidebar %} <ul> <li><a href="/">Home</a></li> <li><a href="/blog/">Blog</a></li> </ul> {% endblock %} </div> <div id="content"> {% block content %}{% endblock %} </div> </body> </html>
假设这个模板叫作 base.html,它定义了一个能够用于两列排版页面的简单HTML骨架。“字模板”的工做是用它们的内容填充的blocks。
在这个例子中,block标签订义了三个能够被子模板内容填充的block。block告诉模板引擎:子模板可能会覆盖掉模板中的这些位置。
子模板可能看起来是这样的:
{% extends "base.html" %} {% block title %}My amazing blog{% endblock %} {% block content %} {% for entry in blog_entries %} <h2>{{ entry.title }}</h2> <p>{{ entry.body }}</p> {% endfor %} {% endblock %}
extends标签是这里的关键。它告诉模板引擎,这个模板“继承”了另外一个模板。当模板系统处理这个模板时,首先,它将定位父模板——在此例中,就是 base.html。
那时,模板引擎将注意到 base.html 中的三个block标签,并用子模板中的内容来替换这些block。根据blog_entries的值,输出可能看起来是这样的:
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style.css" /> <title>My amazing blog</title> </head> <body> <div id="sidebar"> <ul> <li><a href="/">Home</a></li> <li><a href="/blog/">Blog</a></li> </ul> </div> <div id="content"> <h2>Entry one</h2> <p>This is my first entry.</p> <h2>Entry two</h2> <p>This is my second entry.</p> </div> </body> </html>
请注意,子模版并无定义 sidebar block,因此系统使用了父模版中的值。父模版的 {% block %}
标签中的内容老是被用做备选内容(fallback)。这种方式使代码获得最大程度的复用,而且使得添加内容到共享的内容区域更加简单,例如,部分范围内的导航。
下面是使用继承的一些提示:
{% extends %}
标签,它必须是模版中的第一个标签。其余的任何状况下,模版继承都将没法工做。{% block %}
标签越好。请记住,子模版没必要定义所有父模版中的blocks,因此,你能够在大多数blocks中填充合理的默认内容,而后,只定义你须要的那一个。多一点钩子总比少一点好。{% block %}
中。{% endblock %}
标签一个 名字 。例如:{% block content %} ... {% endblock content %}
在大型模板中,这个方法帮你清楚地看到哪个{% block %}
标签被关闭了。