Django模板层


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

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

尽管这种技术便于解释视图是如何工作的,但直接将HTML硬编码到你的视图里却并不是一个好主意。 让我们来看一下为什么:

  • 对页面设计进行的任何改变都必须对 Python 代码进行相应的修改。 站点设计的修改往往比底层 Python 代码的修改要频繁得多,因此如果可以在不进行 Python 代码修改的情况下变更设计,那将会方便得多。

  • Python 代码编写和 HTML 设计是两项不同的工作,大多数专业的网站开发环境都将他们分配给不同的人员(甚至不同部门)来完成。 设计者和HTML/CSS的编码人员不应该被要求去编辑Python的代码来完成他们的工作。

  • 程序员编写 Python代码和设计人员制作模板两项工作同时进行的效率是最高的,远胜于让一个人等待另一个人完成对某个既包含 Python又包含 HTML 的文件的编辑工作。

基于这些原因,将页面的设计和Python的代码分离开会更干净简洁更容易维护。 我们可以使用 Django的 模板系统 (Template System)来实现这种模式,这就是本章要具体讨论的问题。

1 python的模板:HTML代码+模板语法
def current_time(req):
    # ================================原始的视图函数
    # import datetime
    # now=datetime.datetime.now()
    # html="现在时刻:

%s.

" %now # ================================django模板修改的视图函数 # from django.template import Template,Context # now=datetime.datetime.now() # t=Template('现在时刻是:

{{current_date}}

') # #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 模板语法之变量

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

1 {{var_name}}

views.py:

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: 

1 2 3 4 5 6

{{s}}</h4>

列表:{{ l.0 }}</h4>

列表:{{ l.2 }}</h4>

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

日期:{{ date.year }}</h4>

类对象列表:{{ person_list.0.name }}</h4>

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

1

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

2 模板之过滤器

语法:

1 {{obj|filter__name:param}}

default

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

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

length

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

1 {{ value|length }}

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

filesizeformat

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

1 {{ value|filesizeformat }}

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

date

如果 value=datetime.datetime.now()

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

slice

如果 value="hello world"

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

truncatechars

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

参数:要截断的字符数

例如:

1 {{ value|truncatechars:9 }}

safe

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

1 value="">点击"
1 {{ value|safe}}

3 模板之标签 

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

for标签

遍历每一个元素:

{% for person in person_list %}
    

{{ person.name }}

{% endfor %}

可以利用{% for obj in list reversed %}反向完成循环。

遍历一个字典:

{% for key,val in dic.items %}
    

{{ key }}:{{ val }}

{% 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 标签带有一个可选的{% empty %} 从句,以便在给出的组是空的或者没有被找到时,可以有所操作。

{% for person in person_list %}
    

{{ person.name }}

{% empty %}

sorry,no person here

{% endfor %}

if 标签

{% if %}会对一个变量求值,如果它的值是“True”(存在、不为空、且不是boolean类型的false值),对应的内容块会输出。

{% if num > 100 or num < 0 %}
    

无效

{% elif num > 80 and num < 100 %}

优秀

{% else %}

凑活吧

{% endif %}

with

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

例如:

{% with total=business.employees.count %}
    {{ total }} employee{{ total|pluralize }}
{% endwith %}

csrf_token

这个标签用于跨站请求伪造保护

4 自定义标签和过滤器

1、在settings中的INSTALLED_APPS注册当前app,不然django无法找到自定义的simple_tag.

2、在app中创建templatetags文件夹(文件夹名只能是templatetags)

3、创建任意 .py 文件,如:my_tag_filter.py

4、在使用自定义simple_tag和filter的html文件中导入之前创建的 my_tag_filter.py

5、使用simple_tag和filter(如何调用)

注意:filter可以用在if等语句后,simple_tag不可以

my_tag_filter.py

# 先注册app,然后在app下创建templatetags文件夹,文件夹名字必须是这个
# 在templatetags文件夹下创建py文件,register这个变量名必须是这个
from django import template


register = template.Library()


@register.filter
def multi_filter(x, y):
    """
    自定义过滤器只能接收两个参数,参数个数受限制;但是可以配合if标签做判断
    :param x:
    :param y:
    :return:
    """
    return x * y


@register.simple_tag
def multi_tag(x, y, z):
    """
    自定义标签参数无限制,无法配合if标签做判断
    :param x:
    :param y:
    :return:
    """
    return x * y * z

以上知识点代码及文件创建

app01.urls.py

from django.urls import path

urlpatterns = [
    path("templates/", views.templates, name="templates"),
   path("login/", views.login, name="login"), ]

app01.views.py

from django.shortcuts import render, HttpResponse
from django.urls import reverse


def login(request):
    if request.method == "GET":
        print(reverse("app01:login"))
        return render(request, "login.html")
    elif request.method == "POST":
        print(reverse("app01:login"))
        if request.POST.get("user") == "admin" and request.POST.get("pwd") == "123":
            return render(request, "index.html")
        else:
            return HttpResponse("用户名或密码错误...")



def templates(request):
    """
    模板语法:
            变量:{{}}
                1 深度查询 句点符
                2 过滤器
            标签:{%%}
    """
    # 变量
    name = "mike"
    i = 10
    l = ["python", "java", "js"]
    d1 = {"name": "jason", "age": 18}
    b = False
    class Person(object):
        def __init__(self, name, age):
            self.name = name
            self.age = age
    alex = Person("alex", 20)
    egon = Person("egon", 22)
    person_list = [alex, egon]
    from datetime import datetime
    now = datetime.now()
    l1 = []
    file_size = 11111111111
    text = "my name is jack, i like play basketball!"
    link = "click"

    # 标签
    user = None

    return render(request, "show.html", locals())  # locals()传入的形式---{"name": name, ...}

app01.templatetags.my_tag_filter.py

# 先注册app,然后在app下创建templatetags文件夹,文件夹名字必须是这个
# 在templatetags文件夹下创建py文件,register这个变量名必须是这个
from django import template


register = template.Library()


@register.filter
def multi_filter(x, y):
    """
    自定义过滤器只能接收两个参数,参数个数受限制;但是可以配合if标签做判断
    :param x:
    :param y:
    :return:
    """
    return x * y


@register.simple_tag
def multi_tag(x, y, z):
    """
    自定义标签参数无限制,无法配合if标签做判断
    :param x:
    :param y:
    :return:
    """
    return x * y * z

templates.show.html

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>模板语法title>
    <style>
        * {
            cursor: pointer;
        }
        h3 {
            color: red;
        }
        div {
            color: orange;
            width: 100%;
            background-color: gray;
            height: 25px;
        }
    style>
head>
<body>

<h3>模板语法之变量h3>
<p>name:{{ name }}p>
<p>i:{{ i }}p>
<p>l:{{ l }}p>
<p>d1:{{ d1 }}p>
<p>b:{{ b }}p>
<p>alex:{{ alex }}p>
<p>egon:{{ egon }}p>
<p>person_list:{{ person_list }}p>
<hr>

<h3>模板语法之变量之深度查询h3>
<p>l列表第一个元素:{{ l.0 }}p>
<p>d1字典的name键的值:{{ d1.name }}p>
<p>d1字典的name键的值对其使用upper方法:{{ d1.name.upper }}p>
<p>person_list列表第一个元素的实例属性:{{ person_list.0.age }}p>
<hr>

<h3>模板语法之变量之内置过滤器h3>
<p>date过滤器:{{ now|date:"Y-m-d" }}p>
<p>default过滤器:{{ l1|default:"数据为空" }}p>
<p>length过滤器:l列表长度是{{ l|length }}p>
<p>filesizeformat过滤器:{{ file_size|filesizeformat }}p>
<p>slice过滤器:{{ name|slice:"1:-1" }}p>
<p>truncatechars过滤器(按照字符截取,后面三个点也要算入,10代表截取7个字符,空格也算):{{ text|truncatechars:10 }}p>
<p>truncatewords过滤器(按照单词截取):{{ text|truncatewords:2 }}p>
<p>{{ link }} Django在render的时候,把标签进行了转义处理,这样更加安全一些,比如:评论的输入,输入了一些script标签,如果不做这样的处理把标签返回给浏览器,浏览器直接运行加载script标签,很容易造成一些安全问题p>
<p>safe过滤器:{{ link|safe }}p>
<p>add加法过滤器:{{ d1.age|add:100 }}p>
<p>upper过滤器:{{ d1.name|upper }}p>
<hr>

<h3>模板语法之标签h3>
<div>for标签div>
{% for i in l %}
{#forloop.counter0,代表从0开始计数#}
    <p>列表for循环:{{ forloop.counter0 }} {{ i }}p>
{% endfor %}

{% for k in d1 %}
{#forloop.counter,代表从1开始计数#}
    <p>字典for循环:{{ forloop.counter }} {{ k }}p>
{% endfor %}

{% for p in person_list %}
    <p>{{ p.name }}, {{ p.age }}p>
{% endfor %}

{#l1列表有值,就不会执行empty,没有就会执行#}
{% for x in l1 %}
    <p>{{ x }}p>
{% empty %}
    <p>列表为空p>
{% endfor %}

<div>if标签div>
{% if user %}
    <p>
        <a href="">hi {{ user }}a>
        <a href="">注销a>
    p>
{% else %}
    <p>
        <a href="">登录a>
        <a href="">注册a>
    p>
{% endif %} 

<div>with标签div>
{% with person_list.1.name as pl %}
    <p>{{ pl }}p>
{% endwith %}

<div>url标签div>
<p>这里不做演示了,之前已经学过,在form表单的属性action中使用p>

<div>csrf_token标签div>
<p>在form表单里面加上一个csrf_token标签就可以不用注销settings.py中的代码了,打开开发者工具可以看到,form表单里面多了一个input隐藏标签,value是每一次请求都会有不同的值p>
<p>这样能够避免用户一来就提交post请求,在get请求的时候给用户生成一个隐藏input框,name固定,value每次变化,这样就能做一个判断了p>

<div>自定义标签和过滤器div>
{#一定要先导入编写标签或过滤器的py文件#}
{% load my_tag_filter %}
<p>自定义过滤器:{{ i|multi_filter:10 }}p>
<p>自定义标签:{% multi_tag 10 20 30 %}p>

{#自定义过滤器和if标签配合做逻辑判断#}
{% if i|multi_filter:10 > 50 %}
<p>变量大于5p>
    {% else %}
    <p>变量小于5p>
{% endif %}
body>
html>

templates.login.html

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录title>
head>
<body>
<h4>登录页面h4>
<form action="{% url 'app01:login' %}" method="post">
    {% csrf_token %}
    <p>
        账户:
        <input type="text" name="user">
    p>
    <p>
        密码:
        <input type="password" name="pwd">
    p>
    <p>
        <input type="submit" value="提交">
    p>
form>
body>
html>

5 模板继承 (extend)

Django模版引擎中最强大也是最复杂的部分就是模版继承了。模版继承可以让您创建一个基本的“骨架”模版,它包含您站点中的全部元素,并且可以定义能够被子模版覆盖的 blocks 。

通过从下面这个例子开始,可以容易的理解模版继承:




    
    {% block title %}My amazing site{%/span> endblock %}



    

    
{% block content %}{% endblock %}

这个模版,我们把它叫作 base.html, 它定义了一个可以用于两列排版页面的简单HTML骨架。“子模版”的工作是用它们的内容填充空的blocks。

在这个例子中, block 标签定义了三个可以被子模版内容填充的block。 block 告诉模版引擎: 子模版可能会覆盖掉模版中的这些位置。

子模版可能看起来是这样的:

1 2 3 4 5 6 7 8 9 10 {% extends "base.html" %}   {% block title %}My amazing blog{% endblock %}   {% block content %} {% for entry in blog_entries %}     

{{ entry.title }}</h2>     

{{ entry.body }}</p> {% endfor %} {% endblock %}

extends 标签是这里的关键。它告诉模版引擎,这个模版“继承”了另一个模版。当模版系统处理这个模版时,首先,它将定位父模版——在此例中,就是“base.html”。

那时,模版引擎将注意到 base.html 中的三个 block 标签,并用子模版中的内容来替换这些block。根据 blog_entries 的值,输出可能看起来是这样的:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 ="en">     ="stylesheet" href="style.css" />     My amazing blog<</code><code class="python keyword">/</code><code class="python plain">title></code> <code class="python plain"><</code><code class="python keyword">/</code><code class="python plain">head></code>   <code class="python plain"><body></code> <code class="python spaces">    </code><code class="python plain"><div </code><code class="python functions">id</code><code class="python keyword">=</code><code class="python string">"sidebar"</code><code class="python plain">></code> <code class="python spaces">        </code><code class="python plain"><ul></code> <code class="python spaces">            </code><code class="python plain"><li><a href</code><code class="python keyword">=</code><code class="python string">"/"</code><code class="python plain">>Home<</code><code class="python keyword">/</code><code class="python plain">a><</code><code class="python keyword">/</code><code class="python plain">li></code> <code class="python spaces">            </code><code class="python plain"><li><a href</code><code class="python keyword">=</code><code class="python string">"/blog/"</code><code class="python plain">>Blog<</code><code class="python keyword">/</code><code class="python plain">a><</code><code class="python keyword">/</code><code class="python plain">li></code> <code class="python spaces">        </code><code class="python plain"><</code><code class="python keyword">/</code><code class="python plain">ul></code> <code class="python spaces">    </code><code class="python plain"><</code><code class="python keyword">/</code><code class="python plain">div></code>   <code class="python spaces">    </code><code class="python plain"><div </code><code class="python functions">id</code><code class="python keyword">=</code><code class="python string">"content"</code><code class="python plain">></code> <code class="python spaces">        </code><code class="python plain"><h2>Entry one<</code><code class="python keyword">/</code><code class="python plain">h2></code> <code class="python spaces">        </code><code class="python plain"><p>This </code><code class="python keyword">is</code> <code class="python plain">my first entry.<</code><code class="python keyword">/</code><code class="python plain">p></code>   <code class="python spaces">        </code><code class="python plain"><h2>Entry two<</code><code class="python keyword">/</code><code class="python plain">h2></code> <code class="python spaces">        </code><code class="python plain"><p>This </code><code class="python keyword">is</code> <code class="python plain">my second entry.<</code><code class="python keyword">/</code><code class="python plain">p></code> <code class="python spaces">    </code><code class="python plain"><</code><code class="python keyword">/</code><code class="python plain">div></code> <code class="python plain"><</code><code class="python keyword">/</code><code class="python plain">body></code> <code class="python plain"><</code><code class="python keyword">/</code><code class="python plain">html></code> </td> </tr> </tbody> </table> <p>请注意,子模版并没有定义 <code>sidebar</code> block,所以系统使用了父模版中的值。父模版的 <code>{% block %}</code> 标签中的内容总是被用作备选内容(fallback)。</p> <p>这种方式使代码得到最大程度的复用,并且使得添加内容到共享的内容区域更加简单,例如,部分范围内的导航。</p> <p>这里是使用继承的一些提示:</p> <ul> <li> <p>如果你在模版中使用 <code>{% extends %}</code> 标签,它必须是模版中的第一个标签。其他的任何情况下,模版继承都将无法工作。</p> </li> <li> <p>在base模版中设置越多的 <code>{% block %}</code> 标签越好。请记住,子模版不必定义全部父模版中的blocks,所以,你可以在大多数blocks中填充合理的默认内容,然后,只定义你需要的那一个。多一点钩子总比少一点好。</p> </li> <li> <p>如果你发现你自己在大量的模版中复制内容,那可能意味着你应该把内容移动到父模版中的一个 <code>{% block %}</code> 中。</p> </li> <li> <p>If you need to get the content of the block from the parent template, the <code>{{ block.super }}</code> 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 <code>{{ block.super }}</code> will not be automatically escaped (see the next section), since it was already escaped, if necessary, in the parent template.</p> </li> <li> <p>为了更好的可读性,你也可以给你的 <code>{% endblock %}</code> 标签一个 <em>名字</em> 。例如:</p> <table border="0" cellspacing="0" cellpadding="0"> <tbody> <tr> <td class="gutter"> 1 2 3 </td> <td class="code"> <code class="python plain">{</code><code class="python keyword">%</code> <code class="python plain">block content </code><code class="python keyword">%</code><code class="python plain">}</code> <code class="python plain">...</code> <code class="python plain">{</code><code class="python keyword">%</code> <code class="python plain">endblock content </code><code class="python keyword">%</code><code class="python plain">}  </code> </td> </tr> </tbody> </table> <p>在大型模版中,这个方法帮你清楚的看到哪一个  <code>{% block %}</code> 标签被关闭了。</p> </li> <li>不能在一个模版中定义多个相同名字的 <code>block</code> 标签。</li> </ul> </div> <!--conend--> <div class="p-2"></div> <div class="arcinfo my-3 fs-7 text-center"> <a href='/t/etagid35922-0.html' class='tagbtn' target='_blank'>pythonweb框架</a> </div> <div class="p-2"></div> </div> <div class="p-2"></div> <!--xg--> <div class="lbox p-4 shadow-sm rounded-3"> <div class="boxtitle"><h2 class="fs-4">相关</h2></div> <hr> <div class="row g-0 py-2 border-bottom align-items-center"> <div class="col-7 col-lg-11 border-lg-end"> <h3 class="fs-6 mb-0 mb-lg-2"><a href="/a/1-560149.html">【Python之路Day18】Python Web框架之 Django 进阶操作</a></h3> <div class="ltag fs-8 d-none d-lg-block"> </div> </div> </div><div class="row g-0 py-2 border-bottom align-items-center"> <div class="col-7 col-lg-11 border-lg-end"> <h3 class="fs-6 mb-0 mb-lg-2"><a href="/a/1-264303.html">最简易的python web框架的后端实现</a></h3> <div class="ltag fs-8 d-none d-lg-block"> </div> </div> </div><div class="row g-0 py-2 border-bottom align-items-center"> <div class="col-7 col-lg-11 border-lg-end"> <h3 class="fs-6 mb-0 mb-lg-2"><a href="/a/1-91120.html">十四个Python Web框架Hello Wold示例</a></h3> <div class="ltag fs-8 d-none d-lg-block"> </div> </div> </div> <!----> <!----> </div> <!--xgend--> </div> <div class="col-lg-3 col-12 p-0 ps-lg-2"> <!--box--> <!--boxend--> <!--<div class="p-2"></div>--> <!--box--> <div class="lbox p-4 shadow-sm rounded-3"> <div class="boxtitle pb-2"><h2 class="fs-4"><a href="#">标签</a></h2></div> <div class="clearfix"></div> <ul class="m-0 p-0 fs-7 r-tag"> </ul> <div class="clearfix"></div> </div> <!--box end--> </div> </div> </div> </main> <div class="p-2"></div> <footer> <div class="container-fluid p-0 bg-black"> <div class="container p-0 fs-8"> <p class="text-center m-0 py-2 text-white-50">一品网 <a class="text-white-50" href="https://beian.miit.gov.cn/" target="_blank">冀ICP备14022925号-6</a></p> </div> </div> <script> var _hmt = _hmt || []; (function() { var hm = document.createElement("script"); hm.src = "https://hm.baidu.com/hm.js?6e3dd49b5f14d985cc4c6bdb9248f52b"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s); })(); </script> </footer> <script src="/skin/bootstrap.bundle.js"></script> </body> </html>