063.django之模板层

it2023-09-24  68

文章目录

一 模板层(一) 模板简介(二) 模板语法之变量1 **views.py**2 **html** (三) 模板之过滤器1 **语法:**2 重要的过滤器3 需要了解的过滤器 (四) 模板之标签**1 for标签**2 for ... empty3 if 标签4 with5 csrf_token6 代码示例 (五) 自定义标签和过滤器1 自定义过滤器2 自定义标签3 inclusion_tag的使用4 inclusion_tag跟simple_tag有什么不同? (六) 模板的导入和继承1 模板的导入2 模板的继承(母版)3 include 与 extends (七) 静态文件相关1 三种方式2 特殊用法

一 模板层

(一) 模板简介

​ 你可能已经注意到我们在例子视图中返回文本的方式有点特别。 也就是说,HTML被直接硬编码在 Python代码之中。

def current_datetime(request): now = datetime.datetime.now() html = "<html><body>It is now %s.</body></html>" % now return HttpResponse(html) 尽管这种技术便于解释视图是如何工作的,但直接将HTML硬编码到你的视图里却并不是一个好主意。 让我们来看一下为什么: 1)- 对页面设计进行的任何改变都必须对 Python 代码进行相应的修改。 站点设计的修改往往比底层 Python 代码的修改要频繁得多,因此如果可以在不进行 Python 代码修改的情况下变更设计,那将会方便得多。 2)- Python 代码编写和 HTML 设计是两项不同的工作,大多数专业的网站开发环境都将他们分配给不同的人员(甚至不同部门)来完成。 设计者和HTML/CSS的编码人员不应该被要求去编辑Python的代码来完成他们的工作。 3)- 程序员编写 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]})

模版语法重点:

变量:{{ 变量名 }}

1 深度查询 用句点符

2 过滤器

标签:{% % }

(二) 模板语法之变量

DTL:Django Template Language

在 Django 模板中遍历复杂数据结构的关键是句点字符, 语法:{{变量名}}

1 views.py

def template_test(request): name = 'lqz' li = ['lqz', 1, '18'] dic = {'name': 'lqz', 'age': 18} ll2 = [ {'name': 'lqz', 'age': 18}, {'name': 'lqz2', 'age': 19}, {'name': 'egon', 'age': 20}, {'name': 'kevin', 'age': 23} ] ll3=[] class Person: def __init__(self, name): self.name = name def test(self): print('test函数') return 11 @classmethod def test_classmethod(cls): print('类方法') return '类方法' @staticmethod def static_method(): print('静态方法') return '静态方法' lqz = Person('lqz') egon = Person('egon') person_list = [lqz, egon] bo = True te = test() import datetime now=datetime.datetime.now() link1='<a href="https://www.baidu.com">点我<a>' from django.utils import safestring link=safestring.mark_safe(link1) # html特殊符号对照表(http://tool.chinaz.com/Tools/htmlchar.aspx) # 这样传到前台不会变成特殊字符,因为django给处理了 dot='♠' # return render(request, 'template_index.html', {'name':name,'person_list':person_list}) return render(request, 'template_index.html', locals())

2 html

<p>{{ name }}</p> <p>{{ li }}</p> <p>{{ dic }}</p> <p>{{ lqz }}</p> <p>{{ person_list }}</p> <p>{{ bo }}</p> <p>{{ te }}</p> <hr> <h3>深度查询句点符</h3> <p>{{ li.1 }}</p> <p>{{ dic.name }}</p> <p>{{ lqz.test }}</p> <p>{{ lqz.name }}</p> <p>{{ person_list.0 }}</p> <p>{{ person_list.1.name }}</p> <hr> <h3>过滤器</h3> {#注意:冒号后面不能加空格#} <p>{{ now | date:"Y-m-d H:i:s" }}</p> {#如果变量为空,设置默认值,空数据,None,变量不存在,都适用#} <p>{{ name |default:'数据为空' }}</p> {#计算长度,只有一个参数#} <p>{{ person_list |length }}</p> {#计算文件大小#} <p>{{ 1024 |filesizeformat }}</p> {#字符串切片,前闭后开,前面取到,后面取不到#} <p>{{ 'hello world lqz' |slice:"2:-1" }}</p> <p>{{ 'hello world lqz' |slice:"2:5" }}</p> {#截断字符,至少三个起步,因为会有三个省略号(传负数,1,2,3都是三个省略号)#} <p>{{ '刘清政 world lqz' |truncatechars:"4" }}</p> {#截断文字,以空格做区分,这个不算省略号#} <p>{{ '刘清政 是 大帅比 谢谢' |truncatewords:"1" }}</p> <p>{{ link1 }}</p> <p>{{ link1|safe }}</p> <p>{{ link }}</p> <p>♠</p> <p>{{ dot }}</p> {#add 可以加负数,传数字字符串都可以#} <p>{{ "10"|add:"-2" }}</p> <p>{{ li.1|add:"-2" }}</p> <p>{{ li.1|add:2 }}</p> <p>{{ li.1|add:"2" }}</p> <p>{{ li.1|add:"-2e" }}</p> {#upper#} <p>{{ name|upper }}</p> <p>{{ 'LQZ'|lower }}</p> <hr> <h3>模版语法之标签</h3> {#for 循环 循环列表,循环字典,循环列表对象#} <ui> {% for foo in dic %} {{ foo }} {% endfor %} {#也可以混用html标签#} {% for foo in li %} <ul>foo</ul> {% endfor %} </ui> {#表格#} <table border="1"> {% for foo in ll2 %} <tr> <td>{{ foo.name }}</td> <td>{{ foo.age }}</td> </tr> {% endfor %} </table> <table border="1"> {#'parentloop': {}, 'counter0': 0, 'counter': 1, 'revcounter': 4, 'revcounter0': 3, 'first': True, 'last': False}#} {% for foo in ll2 %} <tr> <td>{{ forloop.counter }}</td> <td>{{ foo.name }}</td> <td>{{ foo.age }}</td> </tr> {% endfor %} </table> {% for foo in ll5 %} <p>foo.name</p> {% empty %} <p>空的</p> {% endfor %} <hr> <h3>if判断</h3> {% if name %} <a href="">hi {{ name }}</a> <a href="">注销</a> {% else %} <a href="">请登录</a> <a href="">注册</a> {% endif %} {#还有elif#} <hr> <h3>with</h3> {% with ll2.0.name as n %} {{ n }} {% endwith %} {{ n }} {% load my_tag_filter %} {{ 3|multi_filter:3 }} {#传参必须用空格区分#} {% multi_tag 3 9 10 %} {#可以跟if连用#} {% if 3|multi_filter:3 > 9 %} <p>大于</p> {% else %} <p>小于</p> {% endif %}

注意:句点符也可以用来引用对象的方法(无参数方法):

<h4>字典:{{ dic.name.upper }}<``/``h4>

(三) 模板之过滤器

1 语法:

{{obj|filter__name:param}} 变量名字|过滤器名称:变量

2 重要的过滤器

(1) safe

​ Django的模板中会对HTML标签和JS等语法标签进行自动转义,原因显而易见,这样是为了安全。但是有的时候我们可能不希望这些HTML元素被转义,比如我们做一个内容管理系统,后台添加的文章中是经过修饰的,这些修饰可能是通过一个类似于FCKeditor编辑加注了HTML修饰符的文本,如果自动转义的话显示的就是保护HTML标签的源文件。为了在Django中关闭HTML的自动转义有两种方式,如果是一个单独的变量我们可以通过过滤器“|safe”的方式告诉Django这段代码是安全的不必转义。比如:

value = "<a href="">点击</a>" {{ value|safe}}

(2) date

如果 value=datetime.datetime.now()

{{ value|date: "Y-m-d" }}  

3 需要了解的过滤器

(1) default

如果一个变量是false或者为空,使用给定的默认值。否则,使用变量的值。例如:

{{ value|default:``"nothing"` `}}

(2) length

返回值的长度。它对字符串和列表都起作用。例如:

{{ value|length }}

如果 value 是 [‘a’, ‘b’, ‘c’, ‘d’],那么输出是 4。

(3) filesizeformat

将值格式化为一个 “人类可读的” 文件尺寸 (例如 '13 KB', '4.1 MB', '102 bytes', 等等)。例如:

{{ value|filesizeformat }}

如果 value 是 123456789,输出将会是 117.7 MB。

(4) slice

如果 value=“hello world”

{{ value|``slice``:``"2:-1"` `}}

(5) truncatechars

如果字符串字符多于指定的字符数量,那么会被截断。截断的字符串将以可翻译的省略号序列(“…”)结尾。

**参数:**要截断的字符数

# 例如: {{ value|truncatechars:``9` `}}

4 其它过滤器(了解即可)

(四) 模板之标签

​ 标签看起来像是这样的: {% tag %}。标签比变量更加复杂:一些在输出中创建文本,一些通过循环或逻辑来控制流程,一些加载其后的变量将使用到的额外信息到模版中。一些标签需要开始和结束标签 (例如{% tag %} ...标签 内容 … {% endtag %})。

1 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对象是一个字典 forloop.counter The current iteration of the loop (1-indexed) 当前循环的索引值(从1开始) forloop.counter0 The current iteration of the loop (0-indexed) 当前循环的索引值(从0开始) forloop.revcounter The number of iterations from the end of the loop (1-indexed) 当前循环的倒序索引值(从1开始) forloop.revcounter0 The number of iterations from the end of the loop (0-indexed) 当前循环的倒序索引值(从0开始) forloop.first True if this is the first time through the loop 当前循环是不是第一次循环(布尔值) forloop.last True if this is the last time through the loop 当前循环是不是最后一次循环(布尔值)forloop.parentloop 本层循环的外层循环 parentloop: 父级forloop对象(for循环嵌套) {'parentloop': {}, 'counter0': 0, 'counter': 1, 'revcounter': 6, 'revcounter0': 5, 'first': True, 'last': False}

2 for … empty

for 标签带有一个可选的{% empty %} 从句,以便在给出的组是空的或者没有被找到时,可以有所操作。

{% for person in person_list %} <p>{{ person.name }}</p> {% empty %} <p>sorry,no person here</p> {% endfor %}

3 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 %}

if语句支持 and 、or、==、>、<、!=、<=、>=、in、not in、is、is not判断。

4 with

使用一个简单地名字缓存一个复杂的变量,当你需要使用一个“昂贵的”方法(比如访问数据库)很多次的时候是非常有用的

例如:

{% with total=business.employees.count %} {{ total }} employee{{ total|pluralize }} {% endwith %}不要写成as

5 csrf_token

{% csrf_token %} 这个标签用于跨站请求伪造保护

6 代码示例

# views.py def index(request): ll=['lqz','egon','zs','ls','ww'] # ll=[] dic={'name':'lqz','age':19} count=1 lqzisnbplus='lqz' # b=False b=True user_list=[{'name':'lqz','age':19},{'name':'egon','age':18},{'name':'张三','age':22},{'name':'李四','age':99},{'name':'asdfasdf','age':18},{'name':'暗室逢灯n','age':18}] return render(request, 'index.html', locals()) #index.html <h1>模板语法之标签</h1> <h2>for的用法</h2> {% for l in ll %} {# <p>{{ l }}</p>#} <p><a href="http://127.0.0.1:8080/{{ l }}">{{ l }}</a></p> {% endfor %} <hr> {% for k,v in dic.items %} <p>key值为:{{ k }},value值为{{ v }}</p> {% endfor %} <table border="1"> <tr> <td>id</td> <td>用户名</td> <td>年龄</td> </tr> {% for dic in user_list %} <tr> <td>{{ forloop.counter }}</td> <td>{{ dic.name }}</td> <td>{{ dic.age }}</td> </tr> {% endfor %} </table> <hr> <h2>for ----empty的用法</h2> <ul> {% for l in ll %} <li>{{ l }}</li> {% empty %} <li>没有数据</li> {% endfor %} </ul> <h2>forloop对象</h2> {% for dic in user_list %} {% for key,value in dic.items %} {{ forloop.parentloop.counter }} <p>{{ key }}:{{ value }}</p> {% endfor %} {% endfor %} <h2>if</h2> {% if b %} <p>b是true的</p> {% else %} <p>b是false的</p> {% endif %} <h2>with重命名</h2> {% with forloop.parentloop.counter as aaa %} {{ aaa }} {% endwith %} {% with lqzisnbplus as a %} {{ a }} ----{{ lqzisnbplus }} {% endwith %} <h2>csrf</h2> {% csrf_token %} <input type="text" name="csrfmiddlewaretoken" value="uC35XuP1J2Va74ArYiNw4TMZ0PaZ6V4qvVGCsUQcqiKF5Sr8IrWS0rzpmOmPBrjY"> </body>

(五) 自定义标签和过滤器

1 自定义过滤器

# 1. 自定义过滤器 -第一步:在settings中的INSTALLED_APPS配置当前app,不然django无法找到自定义的filter -第二步:在app中创建templatetags包(包名只能是templatetags,不能改) -第三步:在包内,新建py文件(如:my_tags.py) -第四步:写代码(标签 ) from django import template register = template.Library() @register.filter def my_upper(value): return value.upper() -第五步使用:(模板),先load,再使用 {% load my_tags %} {{ 'aa'|my_upper }} my_tags.py # 代码示例 # 自定义过滤器: @register.filter def my_upper(value): return value.upper() @register.filter def my_add(a, b): return a + b views.py # 代码示例 # 自定义过滤器 def index(request): return render(request, 'index00.html', context={'a': 5, 'b': 1}) # 注意:参数需要在视图函数中传入,以字典的形式,另外,如果数据需要查询,则在视图函数中写相关的查询代码。

2 自定义标签

# 2. 自定义标签 -第一步:在settings中的INSTALLED_APPS配置当前app,不然django无法找到自定义的simple_tag -第二步:在app中创建templatetags包(包名只能是templatetags,不能改) -第三步:在包内,新建py文件(如:my_tags.py) -第四步:写代码(过滤器) from django import template register = template.Library() @register.simple_tag def my_csrf(): import uuid res=uuid.uuid4() return mark_safe('<input type="hidden" name="csrfmiddlewaretoken" value="%s">'%res) -第五步使用:(模板),先load,再使用 {% load my_tags %} {% my_csrf %} {% my_tag 1 3 4 %} #### 参数的传递,通过一个空格分隔 my_tags.py # 代码示例 # 自定义标签,没有参数 @register.simple_tag def my_csrf(): import uuid res = uuid.uuid4() return mark_safe('<input type="hidden" name="csrfmiddlewaretoken" value="%s">' % res) # 标签,有参数 @register.simple_tag def my_tag(a, b, c): return a + b + c

3 inclusion_tag的使用

# 可以生成一片模板中的代码块 # 使用:5步 -第一步:在settings中的INSTALLED_APPS配置当前app,不然django无法找到自定义的inclusion_tag -第二步:在app中创建templatetags包(包名只能是templatetags,不能改) -第三步:在包内,新建py文件(如:my_tags.py) -第四步:写代码(inclusion_tag) # inclusion_tag,传一个模板文件 @register.inclusion_tag('left.html') def left(num): # dic={0:第0页,1:第1页,2:第2页} dic = {i: '第%s页' % i for i in range(num)} # 固定返回的必须是字典 print(dic) return {'data': dic} @register.inclusion_tag('beautiful.html') def beautiful(title, url): return {'title': title, 'url': url} -第五步使用:(模板),先load,再使用 {% load my_tags %} {% left 5%} {% beautiful '名字' '地址'%} my_tags.py # 代码示例 # inclusion_tag,传一个模板文件 @register.inclusion_tag('left.html') def left(num): # dic = {0:第0页,1:第一页, 2:第二页} dic = {i: '第%s页' % i for i in range(num)} # 固定返回必须是字典 print(dic) return {'data': dic} my_tags.py # 代码示例 ### 通过simple_tag实现 inclusion_tag的功能 @register.simple_tag def tab_former02(title, url): return mark_safe(""" <div class="panel panel-danger"> <div class="panel-heading"> <h3 class="panel-title"> %s </h3> </div> <div class="panel-body"> 详情点击:<a href=" %s ">疯狂点我</a> </div> </div> """ % (title, url))

4 inclusion_tag跟simple_tag有什么不同?

# 它跟simple_tag有什么不同? -simple_tag需要在代码中写html的东西 -inclusion_tag代码跟html模板分离,【代码中返回的字典,相当于context,去渲染模板】

(六) 模板的导入和继承

1 模板的导入

# 1. 模板的导入 -第一步:新建一个 xx.html,把好看的模板写入 <div class="panel panel-danger"> <div class="panel-heading"> <h3 class="panel-title">重金求子</h3> </div> <div class="panel-body"> 详情点击:<a href="http://www.baidu.com">疯狂点我</a> </div> </div> -第二步:在你想用的地方 {% include 'xx.html' %}

2 模板的继承(母版)

# 2. 模板的继承(母版) -第一步:写一个母版,写空盒子 {% block top %} {% endblock %} -第二步:某个页面要使用母版,引入,扩写盒子 {% extends 'base.html' %} {% block top %} index页面 {% endblock %}

3 include 与 extends

# 3. include 与 extends -include:加载模板并使用当前上下文呈现它。这是在模板中“包含”其他模板的一种方式。模板名称可以是变量,也可以是硬编码(带引号)的字符串,用单引号或双引号引起来。【本质是with open 之后替换,一般用于头部、尾部不变的部分。常常用于局部】 -extends:表示此模板扩展了父模板。【可以任意扩展】

(七) 静态文件相关

1 三种方式

# 三种方式 第一种: <link rel="stylesheet" href="/static/bootstrap/css/bootstrap.min.css"> 第二种: {% load static %} <link rel="stylesheet" href="{% static 'bootstrap/css/bootstrap.min.css' %}"> 第三种: {% load static %} <link rel="stylesheet" href="{% get_static_prefix %}bootstrap/css/bootstrap.min.css">

2 特殊用法

# 特殊用法 {% load static %} {% static "images/hi.jpg" as myphoto %} <img src="{{ myphoto }}"></img> {% load static %} {% get_static_prefix as static %} <img src="{{ static }}images/hi.jpg" alt="Hi!" />
最新回复(0)