• 模板层


    一、模板简介

        视图函数的主要作用是生成请求的响应,这是最简单的请求。
        实际上,视图函数有两个作用:处理业务逻辑和返回响应内容。在大型应用中,把业务逻辑和表现内容放在一起,会增加代码的复杂度和维护成本。本节学到的模板,它的作用即是承担视图函数的另一个作用,即返回响应内容。

    使用模板的好处

    #视图函数只负责业务逻辑和数据处理(业务逻辑方面)
    #而模板则取到视图函数的数据结果进行展示(视图展示方面)
    #代码结构清晰,耦合度低

    两种给模板传递值的方式

    # 方式一、return render(request,'login.html',{"s":s,"num":num,"l":l,"d":dic})
                                                         HTML中的标签对应的是该处的key
                                                         <p>{{ d }}</p>    
        
    #方式二、return render(request, 'index.html', locals()) #会将当前的名称空间所有变量名传给前端      

     

    变量相关{{}}
    逻辑相关{%%}

                                                        ---模板语言之变量---

    模板页面中对变量的使用
    #语法
      {{变量}}-------->>相当于print了该变量
    #-支持数字,字符串,布尔类型,列表,字典---相当于对它进行了打印
    #-函数--->相当于加括号运行(不能传参数)
    #-对象--->内存地址,(如果重写__str__方法,打印的就是返回的内容)

    深度查询

    #统一用句点符(.)
    #列表套列表,或字典套字典等嵌套关系的,用点点点,一直点出来为止

    def index(request):
        name = 'lqz'
        age = 18
        ll = [1, 2, 'lqz', 'egon']
        ll2=[]
        dic2={}
        tu = (1, 2, 3)
        dic = {'name': 'lqz', 'age': 18, 'll': [1, 2, 4]}
    
        # 函数
        def test():
            print('lqz')
            return 'zhouxiang dsb'
    
        # 在模板上相当于执行该函数,并打印
        print(test())
    
        # 类和对象
        class Person():
            def __init__(self, name, age):
                self.name = name
                self.age = age
            def get_name(self):
                return self.name
            @classmethod
            def cls_test(cls):
                return 'cls'
            @staticmethod
            def static_test():
                return 'static'
            # 模板里不支持带参数
            def get_name_cs(self,ttt):
                return self.name
        lqz=Person('lqz',18)
        egon=Person('egon',18)
        person_list=[lqz,egon]
        person_dic={'lqz':lqz}
    
        file_size=1024
        import datetime
        ctim=datetime.datetime.now()
    
        h1='<h1>你好</h1>'
        script='<script>alert(111)</script>'
    
        # user='lqz'
        user=''
    
        # return render(request,'index.html',{'name':name})
        # locals() 会把*该*视图函数内的变量,传到模板
        return render(request, 'index.html', locals())
    练习,,views
    <body>
    <hr>
    {#模板语言注释:前端看不到#}
    {#相当于print了该变量#}
    <h1>模板语言之变量</h1>
    <p>字符串:{{ name }}</p>
    <p>数字:{{ age }}</p>
    <p>列表:{{ ll }}</p>
    <p>元祖:{{ tu }}</p>
    <p>字典:{{ dic }}</p>
    {#只写函数名:相当于函数名(),执行该函数#}
    <p>函数:{{ test }}</p>
    {#对象内存地址#}
    <p>对象:{{ lqz }}</p>
    <p>列表套对象:{{ person_list }}</p>
    <p>字典套对象:{{ person_dic }}</p>
    <hr>
    <h1>深度查询</h1>
    <p>列表第0个值:{{ ll.0 }}</p>
    <p>列表第3个值:{{ ll.3 }}</p>
    <p>字典取值:{{ dic.name }}</p>
    <p>字典取列表值:{{ dic.ll }}</p>
    {#再继续取值,继续点#}
    <p>对象取数据属性:{{ lqz.name }}</p>
    <p>对象取绑定给对象的函数属性:{{ lqz.get_name }}</p>
    <p>对象取绑定给类的函数属性:{{ lqz.cls_test }}</p>
    <p>对象取静态方法:{{ lqz.static_test }}</p>
    <p>把对象列表中egon年龄取出来:{{ person_list.1.age }}</p>
    {#拓展:不能调有参数的方法#}
    <p>字符串的方法:{{ name.upper }}</p>
    练习,,HTML

         

                                     ---模板之过滤器---

    语法:

    {{变量的名字|过滤器名称:变量}}

      |右边其实就是一个函数
      |左边的值当做第一个位置参数传给过滤器,
      冒号后边的当做第二个位置参数传递给过滤器
    例如 <p>过滤器之默认值:{{ li|default:'没有值' }}</p>

    常用过滤器

    1、length

    #返回值的长度,它对字符串和列表都起作用,
    {{value|length}}
    
    #如果value是['a','b','c','d']那么输出的值为4

    2、filesizeformat

    #将值转换为“人类可读”的文件尺寸
    <p>{{ size|filesizeformat }}</p>
    
    其中views中的size=1024,输出为1.0 KB

    4、date

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

    5、slice

    #切片,支持负数,支持步长
    <p>{{ s|slice:'1:-3:2 '}}</p>

    6、truncatechars

    #如果字符串多余指定的字符数量,会把多余的部分用省略号代替(并且省略号占3个)
    
    text ="我们看新闻时,为了显示一部分,总是有省略号"
    
    <p>{{ text|truncatechars:5}}</p>
    
    >>我们...       #这里指示的是5,只显示出两个,是因为省略号占了3个
    
    
    
    truncatewords
      按照空格的数量计数
    text ="我们看新闻时 为了显示一部分 总是有省略号"
    <p>{{ text|truncatewords:2}}</p>
    
    >>我们看新闻时 为了显示一部分 ...     #这里省略号不占位数

    7、safe

    #|safe  取消转义
    
    #非取消转义
    text = "<p>这是p标签</p>"
    在HTML中直接执行
    <p>{{ text}}</p>
    输出
    <p>这是p标签</p>
    
    ----------------------------------------------------
    #前端取消转义(|safe)
    <p>{{ text|safe }}</p>   #safe安全的
    输出
    这是p标签
    
    #后端
    from django.utils.safestring import mark_safe
    text = mark_safe("<h1>我是h1</h1>")

    8、add

    数字相加,字符串拼接

    <p>过滤器之用add:{{ 12|add:'1' }}</p>                 -------->13
    <p>过滤器之用add:{{ 'lb'|add:'pdun' }}</p>            -------->lbpdun


     

        

          ---模版之标签---

    一、for标签

      遍历每一个元素:(可以利用 {% for obj in list reversed %} 反向解析)

    {% for i in "12345"%}        #如果此处为12345,不可迭代,但可用make_list转为列表
        <p>{{ i }}</p>
    {% endfor %}

      遍历一个字典:

    {% for key,val in dic.items %}
        <p>{{ key }}:{{ val }}</p>
    {% endfor %}

      注:循环序号可以通过{{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': {}, 'counter0': 0, 'counter': 1, 'revcounter': 8, 'revcounter0': 7, 'first': True, 'last': False}
    
    {'parentloop': {}, 'counter0': 1, 'counter': 2, 'revcounter': 7, 'revcounter0': 6, 'first': False, 'last': False}
    
    {'parentloop': {}, 'counter0': 2, 'counter': 3, 'revcounter': 6, 'revcounter0': 5, 'first': False, 'last': False}
    
    {'parentloop': {}, 'counter0': 3, 'counter': 4, 'revcounter': 5, 'revcounter0': 4, 'first': False, 'last': False}
    
    {'parentloop': {}, 'counter0': 4, 'counter': 5, 'revcounter': 4, 'revcounter0': 3, 'first': False, 'last': False}
    
    {'parentloop': {}, 'counter0': 5, 'counter': 6, 'revcounter': 3, 'revcounter0': 2, 'first': False, 'last': False}
    
    {'parentloop': {}, 'counter0': 6, 'counter': 7, 'revcounter': 2, 'revcounter0': 1, 'first': False, 'last': False}
    
    {'parentloop': {}, 'counter0': 7, 'counter': 8, 'revcounter': 1, 'revcounter0': 0, 'first': False, 'last': True}
    forloop

     

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

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

     

     

    三、with  

    相当于取别名,简化书写

    例如:

    {% with total=business.employees.count %}
        {{ total }} employee{{ total|pluralize }}
    {% endwith %}
    
    #注意:等号左右不能有空格(total后的等号)
    
    这里使用了=号,也可使用as

    csrf_token

    {% csrf_token%}

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

     
     
                         ---自定义标签和过滤器---
    三步骤
    1、在settings中的INSTALLED_APPS配置当前app
    2、在APP下建立一个名字必须为templatetags的文件夹 3、在文件夹下建立任意名字的py文件
    #在创建的文件夹下
    
    #第一步,导入
    from django import template
    #第二步,定义一个叫register的变量=template.Library
    register = template.Library()
    #自定义过滤器
    @register.filter(name="jump")      #name=“”为取别名(该参数可不传
    def filter_multi(value,arg):
        try:
            return value*int(arg)
        except (ValueError,TypeError):
            return ""
    
    #自定义标签
    @register.simple_tag(name='add_there')      
    def zero_add(arg1,arg2,arg3):
        try:
            return int(arg1)+int(arg2)+int(arg3)
        except (ValueError,TypeError):
            return ""
    
    
    ---------------------------html
    <body>
    
    {% load my_tags %}        #使用的时候先load,,,,后边的(my_tags)是py文件的名字
    <p>{{ '123'|jump:2}}</p>
    <p>{{ 123|jump:2}}</p>
    
    <p>{% add_there 10 20 30  %}</p>
    
    </body>

    有时间自己写一个自定义的safe

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

    {% if num|filter_multi:30 > 100 %}
        {{ num|filter_multi:30 }}
    {% endif %}

    六 模版导入入和继承

    模版导入:

      在templates中创建一个HTML文件,清空里边的东西,然后写自己的东西

      {% include '模版名称' %}

     

    <div class="adv">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">Panel title</h3>
            </div>
            <div class="panel-body">
                Panel content
            </div>
        </div>
        <div class="panel panel-danger">
            <div class="panel-heading">
                <h3 class="panel-title">Panel title</h3>
            </div>
            <div class="panel-body">
                Panel content
            </div>
        </div>
        <div class="panel panel-warning">
            <div class="panel-heading">
                <h3 class="panel-title">Panel title</h3>
            </div>
            <div class="panel-body">
                Panel content
            </div>
        </div>
    </div>
    adv.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.min.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>
            * {
                margin: 0;
                padding: 0;
            }
    
            .header {
                height: 50px;
                 100%;
                background-color: #369;
            }
        </style>
    </head>
    <body>
    <div class="header"></div>
    
    <div class="container">
        <div class="row">
            <div class="col-md-3">
                {% include 'adv.html' %}
    
    
            </div>
            <div class="col-md-9">
                {% block conn %}
                    <h1>你好</h1>
                {% endblock %}
    
            </div>
        </div>
    
    </div>
    
    </body>
    </html>
    base.html
    {% extends 'base.html' %}
    
    {% block conn %}
        {{ block.super }}
    是啊
    
    {% endblock conn%}
    order.html

     

    模版继承

    # 模板的继承
        1 写一个母版,留一个可扩展的区域(盒子),可以留多个盒子(留的越多,可扩展性越高)
            {%block 名字%}
                可以写内容
            {%endblock%}
        
        #2 在子模板中使用:
            {%block 名字%}   #这里边添加名字,在模板较多时,不容易混淆
                子模板的内容
            {%endblock 名字%}
    复制代码
    <!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 %} 标签,它必须是模版中的第一个标签。其他的任何情况下,模版继承都将无法工作。

    • 在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 %} 标签被关闭了。

    • 不能在一个模版中定义多个相同名字的 block 标签。

    七 静态文件相关

    #为了避免settings中的static改变,无法找到static文件中的css等静态文件,所以需要动态获得static
    
    例如
    #1 写死静态文件:<link rel="stylesheet" href="/static/css/mycss.css">
    #2 使用 static标签函数:
      -{%load static%}
      #static返回值,会拼上传参的路径
      -{% static "传参"%}
    #3 使用get_static_prefix 标签
      -{%load static%}
      #get_static_prefix返回值是:静态文件的地址,相当于/static/
      -{% get_static_prefix %}css/mycss.css
    
     
    方式一

    {% load static %} <img src="{% static "images/hi.jpg" %}" alt="Hi!" />

    引用JS文件时使用:

    #{% load static %}
    <script src="{% static "mytest.js" %}"></script>

    某个文件多处被用到可以存为一个变量

    {% load static %}
    {% static "images/hi.jpg" as myphoto %}
    <img src="{{ myphoto }}"></img>

    使用get_static_prefix

    {% load static %}
    <img src="{% get_static_prefix %}images/hi.jpg" alt="Hi!" />

    或者

    {% load static %}
    {% get_static_prefix as STATIC_PREFIX %}
    
    <img src="{{ STATIC_PREFIX }}images/hi.jpg" alt="Hi!" />
    <img src="{{ STATIC_PREFIX }}images/hi2.jpg" alt="Hello!" />

    inclusion_tag

    多用于返回html代码片段

    示例:

    templatetags/my_inclusion.py

    复制代码
    复制代码
    from django import template
    
    register = template.Library()
    
    
    @register.inclusion_tag('result.html')
    def show_results(n):
        n = 1 if n < 1 else int(n)
        data = ["第{}项".format(i) for i in range(1, n+1)]
        return {"data": data}
    复制代码
    复制代码

    templates/snippets/result.html

    <ul>
      {% for choice in data %}
        <li>{{ choice }}</li>
      {% endfor %}
    </ul>

    templates/index.html

    复制代码
    复制代码
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta http-equiv="x-ua-compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>inclusion_tag test</title>
    </head>
    <body>
    
    {% load inclusion_tag_test %}
    
    {% show_results 10 %}
    </body>
    </html>
    复制代码
    复制代码
  • 相关阅读:
    traceroute命令
    ifconfig命令
    netstat命令
    ps命令
    Vue3.0新特性
    Shadow DOM的理解
    解决ufw下pptp客户端连接问题
    Event对象
    java面试一日一题:讲下mysql中的索引
    java面试一日一题:讲下mysql中的redo log
  • 原文地址:https://www.cnblogs.com/pdun/p/10720082.html
Copyright © 2020-2023  润新知