直接将HTML硬编码到视图里并非一个好主意。 让咱们来看一下为何:css
from django.shortcuts import render,HttpResponse import datetime def current_datetime(request): now = datetime.datetime.now() html = '<html><body>It is now %s</body></html>' % now return HttpResponse(html)
对页面设计进行的任何改变都必须对 Python 代码进行相应的修改。 站点设计的修改每每比底层 Python 代码的修改要频繁得多,所以若是能够在不进行 Python 代码修改的状况下变动设计,那将会方便得多。html
Python 代码编写和 HTML 设计是两项不一样的工做,大多数专业的网站开发环境都将他们分配给不一样的人员(甚至不一样部门)来完成。 设计者和HTML/CSS的编码人员不该该被要求去编辑Python的代码来完成他们的工做。python
程序员编写 Python代码和设计人员制做模板两项工做同时进行的效率是最高的,远胜于让一我的等待另外一我的完成对某个既包含 Python又包含 HTML 的文件的编辑工做。程序员
基于这些缘由,将页面的设计和Python的代码分离开会更干净简洁更容易维护。 咱们可使用 Django的 模板系统 (Template System)来实现这种模式数据库
python的模板:HTML代码+模板语法django
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]})
模板语法
1.渲染变量{{ }}
1.深度查询 句点符
语法:{{var_name}}
<p>{{ alex.age }}</p>
<p>{{ person_list.1.age }}</p>
2.过滤器
语法:{{obj|filter__name:param}}
按照某种形式渲染出来
<p>{{ now|date:'Y-m-d' }}</p>
<p>{{ info.name|upper }}</p>
2.渲染标签{% %}
语法:{% tag %}
...
示例:bootstrap
views.py缓存
from django.shortcuts import render,HttpResponse def index(request): #============================模板语法之变量=================================== import datetime s = 'hello' li = [111,222,333] dic = {'name':'alce','age':22} date = datetime.date(2018,5,21) class Person(object): def __init__(self,name): self.name = name person_yuan = Person('yuan') person_alex = Person('alex') person_egon = Person('egon') person_list = [person_yuan,person_alex,person_egon] # return render(request,'index.html',{'s':s}) # 全部得变量都会传到模板中 return render(request,'index.html',locals())
index.html安全
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <h3>模板语法之变量</h3> <p>{{ s }}</p> <p>{{ li }}</p> <p>{{ li.1 }}</p> <p>{{ dic }}</p> <p>{{ dic.name }}</p> <p>{{ date }}</p> <p>{{ date.year }}</p> <p>{{ person_alex }}</p> <p>{{ person_alex.name }}</p> <p>{{ person_list }}</p> <p>{{ person_list.1.name }}</p> <p>{{ person_list.1.name.upper }}</p> # 句点符也能够用来引用对象的方法(无参数方法): </body> </html>
default
app
若是一个变量是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"
}}
若是字符串字符多于指定的字符数量,那么会被截断。截断的字符串将以可翻译的省略号序列(“...”)结尾。
参数:要截断的字符数
例如:
{{ 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 person in person_list %} <p>{{ person.name }}</p> {% endfor %}
能够利用{% for obj in list reversed %}反向完成循环。
遍历一个字典:
{% for key,val in dic.items %} <p>{{ key }}:{{ val }}</p> {% endfor %}
注:循环序号能够经过{{forloop}}显示
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 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 %}
{# 深度查询 很是长得 时候 能够用with #}
{% with person_list.1.name as n %}
{{ n }}
{{ n }}
{% endwith %}
这个标签用于跨站请求伪造保护
为了保留django 留给咱们得 安全机制 django 得中间见
只要发 post 请求 ,{ % csrf_token %} 为了安全机制
{ % csrf_token %} 解决办法
< input
type = 'hidden'
name = 'csrfmiddlewaretoken'
value = 'OqNwoXIbFSTI3qxdtqKppQuZvlWebFgw9vSAkGXrGX4J2wo9t7OWDXvyxU4asBRE' / >
一、在settings中的INSTALLED_APPS配置当前app,否则django没法找到自定义的simple_tag.
二、在app中建立templatetags模块(模块名只能是templatetags)
三、建立任意 .py 文件,如:my_tag_filter.py
from django import template from django.utils.safestring import mark_safe # register的名字是固定的,不可改变 register = template.Library() # 自定义过滤器 @register.filter def multi_filter(x,y): return x*y # 自定义标签 @register.simple_tag def multi_tags(x,y,z): return x*y*z @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_tag_filter.py
{% load my_tag_filter %}
五、使用simple_tag和filter(如何调用)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <h3>自定义标签 过滤器</h3> {% load my_tag_filter %} {# num = 4 8 #} {{ num|multi_filter:2 }} {# 2*3*4 = 24 #} {# 参数不限,但不能放在if for语句中 #} {% multi_tags 2 3 4 %} {% if num|multi_filter:2 > 20 %} {{ num|multi_filter:2 }} {% else %} {{ num }} {% endif %} {# 注意:filter能够用在if等语句后,tag不能够 #} {% my_input 2 'active' %} </body> </html>
注意:filter能够用在if等语句后,simple_tag不能够
{% if num|multi_filter:2 > 20 %}
{{ num|multi_filter:2 }}
{% else %}
{{ num }}
{% endif %}
Django模版引擎中最强大也是最复杂的部分就是模版继承了。模版继承可让您建立一个基本的“骨架”模版,它包含您站点中的所有元素,而且能够定义可以被子模版覆盖的 blocks 。
经过从下面这个例子开始,能够容易的理解模版继承:
base.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> {% block title %} <title>base</title> {% endblock %} <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <style type="text/css"> *{padding: 0;margin: 0;} .header{ width: 100%;height: 50px;background-color: #369} </style> </head> <body> <div class="header"></div> <div class="container"> <div class="col-md-3"> {% include 'advertise.html' %} </div> <div class="col-md-9"> {% block con %} <h1>content</h1> {% endblock %} </div> </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 %}
标签,它必须是模版中的第一个标签。其余的任何状况下,模版继承都将没法工做。
在base模版中设置越多的 {% block %}
标签越好。请记住,子模版没必要定义所有父模版中的blocks,因此,你能够在大多数blocks中填充合理的默认内容,而后,只定义你须要的那一个。多一点钩子总比少一点好。
若是你发现你本身在大量的模版中复制内容,那可能意味着你应该把内容移动到父模版中的一个 {% block %}
中。
If you need to get the content of the block from the parent template, the {{ block.super }}
variable will do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it. Data inserted using {{ block.super }}
will not be automatically escaped (see the next section), since it was already escaped, if necessary, in the parent template.
为了更好的可读性,你也能够给你的 {% endblock %}
标签一个 名字 。例如:
{% block content %}
...
{% endblock content %}
在大型模版中,这个方法帮你清楚的看到哪个 {% block %}
标签被关闭了。
block
标签。
示例: