Django的模板层
虽然HTML被直接硬编码在 Python代码之中,可以便于解释视图是如何工作的,但是直接HTML硬编码到你的视图里去不是个好东西,原因 :
-
对页面设计进行的任何改变都必须对 Python 代码进行相应的修改。 站点设计的修改往往比底层 Python 代码的修改要频繁得多,因此如果可以在不进行 Python 代码修改的情况下变更设计,那将会方便得多。
-
Python 代码编写和 HTML 设计是两项不同的工作,大多数专业的网站开发环境都将他们分配给不同的人员(甚至不同部门)来完成。 设计者和HTML/CSS的编码人员不应该被要求去编辑Python的代码来完成他们的工作。
-
程序员编写 Python代码和设计人员制作模板两项工作同时进行的效率是最高的,远胜于让一个人等待另一个人完成对某个既包含 Python又包含 HTML 的文件的编辑工作。
基于这些原因,将页面的设计和Python的代码分离开会更干净简洁更容易维护。 我们可以使用 Django的 模板系统 (Template System)来实现这种模式 :
#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
from django.shortcuts import render import datetime def index(request): s="hello" age=66 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_tom=Person("tom") person_list=[person_yuan,person_egon,person_tom] return render(request,"index.html",{"l":l,"dic":dic,"date":date,"person_list":person_list}) #如果前面的所有数据都要到HTML中,可以将 {}-->>>locals().
template-->HTML
<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>
模板的 过滤器
语法 :
{{ value|filter_name:param}} #value : 变量名 #filter__name: 过滤器 #param : 条件
default
如果一个变量为空或者false,使用给定的默认值.否则,使用变量的值.
{{ value|default:"没有了呢!" }}
length
返回值得长度,它对字符串和列表起作用 :
{{ value|length }}
如果 value = ["a","b","c"] ,输出为 3
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" }}
返回的结果 ; 2018-10-23
slice
如果 value="hello world"
{{ value|slice:"2:-1" }}
返回结果 : llo worl (类似于字符串的切片)
truncatechars
如果字符串字符多于指定的字符数量,那么会被截断。截断的字符串将以可翻译的省略号序列(“...”)结尾。
参数:要截断的字符数
# value = "I believe,for every drop of rain,that falls, A flower grows,I believe that somewhere in the,darkest night, A candle glows" {{ value|truncatechars:20 }} #返回结果 : I believe,for eve... # 要截断的是20个字符,但是只会截断到17,要留3个给省略号.
safe
Django的模板中会对HTML标签和JS等语法标签进行自动转义,原因显而易见,这样是为了安全。但是有的时候我们可能不希望这些HTML元素被转义,比如我们做一个内容管理系统,后台添加的文章中是经过修饰的,这些修饰可能是通过一个类似于FCKeditor编辑加注了HTML修饰符的文本,如果自动转义的话显示的就是保护HTML标签的源文件。为了在Django中关闭HTML的自动转义有两种方式,如果是一个单独的变量我们可以通过过滤器“|safe”的方式告诉Django这段代码是安全的不必转义。比如:
value="<a href="">点击</a>" {{ value|safe}}
过滤器示例 :
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.shortcuts import render def index(request): import datetime now=datetime.datetime.now() book_list=["悲惨世界","三天光明","贝加尔湖畔"] s="hollo moto" size=123456789999 str="hello world" read="I believe,for every drop of rain,that falls, A flower grows,I believe that somewhere in the,darkest night, A candle glows" link="<a href='http://www.baidu.com'>点我</a>" return render(request,"index.html",locals())
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<h3>过滤器</h3> <p>{{ now|date:"Y-m-d" }}</p> <p>{{ book_list|default:"没有了呢" }}</p> <p>{{ book_list.3|default:"没有了呢" }}</p> <p>{{ s|length }}</p> <p>{{ size|filesizeformat }}</p> <p>{{ str|slice:"2:-1" }}</p> <p>{{ read|truncatechars:20 }}</p> <p>{{ link }}</p> <p>{{ link|safe }}</p>
模板的 标签
标签看起来像是这样的: {% tag %}
。标签比变量更加复杂:一些在输出中创建文本,一些通过循环或逻辑来控制流程,一些加载其后的变量将使用到的额外信息到模版中。一些标签需要开始和结束标签 (例如{% tag %} ...
标签 内容 ... {% endtag %})。
for 标签
遍历每一个元素 :
比如 : person_list = ["悲惨世界","三天光明","贝加尔湖畔"]
{% for person in person_list %} <p>{{ person }}</p> {% endfor %} <ul> {% for person in person_list %} <li>{{ person }}</li> {% endfor %} </ul>
注意 : 可以利用 {% for obj in list reversed %}反向完成循环.
遍历一个字典 :
{% for key,val in dic.items %} <p>{{ key }}:{{ val }}</p> {% endfor %}
注意 : 循环序号可以通过{{ forloop }} 显示
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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>没有了呢</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
用于跨站请求伪造保护 (post 请求的时候放到 HTML 里的from 表单里即可),这样我们就不用去注销setting里面的 'django.middleware.csrf.CsrfViewMiddleware'.
自定义 过滤器 和 标签
点击查看---------->●●●●●●
模板的 继承
如果我们创建一个网站,有首页,订单,和商品列表,订单和商品列表一定属于是子网页,但是我们又希望,我们网页里面只有中间的区域改变,顶部和底部,左面的样式和内容是不变的,但是这样会有很多的重复的代码,这个时候就可以使用继承了.
示例 :
<!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="style.css" /> <title>{% block title %}My amazing site{%/span> 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
告诉模版引擎: 子模版可能会覆盖掉模版中的这些位置。
子模版可能看起来是这样的:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
{% 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
的值,输出可能看起来是这样的:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!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
标签。
示例 :
urls.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', views.index),
path('order/', views.order),
path('shopping_list/', views.shopping_list),
]
views.py
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from django.shortcuts import render
def index(request):
return render(request,"index.html")
def order(request):
order_list=["订单1","订单2","订单3"]
return render(request,"order.html",{"order_list":order_list})
def shopping_list(request):
shopping_list=["苹果","香蕉","苹果"]
return render(request,"shopping_list.html",{"shopping_list":shopping_list})
templates-->
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> {% block title %} <title>Title</title> {% endblock %} <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- 最新版本的 Bootstrap 核心 CSS 文件 --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <style> *{ margin: 0; padding: 0; } .header{ width: 100%; height: 50px; background-color: #369; } </style> </head> <body> <div class="header"></div> <div class="container"> <div class="row"> <div class="col-md-3"> {% block menu %} <div class="panel panel-success"> <div class="panel-heading">Panel heading without title</div> <div class="panel-body"> <p><a href="/index/">首页</a></p> <p><a href="/order/">订单</a></p> <p> <a href="/shopping_list/">商品列表</a></p> </div> </div> {% endblock %} </div> <div class="col-md-9"> {% block content %} <h3>welcome!</h3> {% endblock content%} </div> </div> </div> </body> </html>
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
{% extends "base.html" %} #引入母板 {% block content %} {{ block.super }} #继承母板本身就有的,不改变 <div class="jumbotron"> <h1>Hello, world!</h1> <p>...</p> <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p> </div> {% endblock %} {% block title %} <title>首页</title> {% endblock %}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
{% extends "base.html" %} {% block content %} <h3>订单列表</h3> {% for order in order_list %} <p>{{ order }}</p> {% endfor %} {% endblock %} {% block title %} #放到哪里无所谓,有名字 <title>订单</title> {% endblock %}
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
{% extends "base.html" %} {% block title %} <title>商品列表</title> {% endblock %} {% block content %} <h3>商品列表</h3> {% for foo in shopping_list %} <p>{{ foo }}</p> {% endfor %} {% endblock %}
注意 : 1 . 使用模板继承,{% extends %} 必须放在最前面.
2 . {% block %} 和 {% endblock %} 要成对出现.
3 . 可以给 {% block %} 和 {% endblock %} 起个名字,方便可读性,母板什么名字,要改变的子板就要什么名字.
4 . 模板的继承,有{% block %} 和 {% endblock %} 的是子页面要改变的内容,如果加
{% block.super%} 表示同时保留母板中的内容.