• Django模板层


    一、模版简介

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

    def current_datetime(request):
        now = datetime.datetime.now()
        html = "It is now %s." % now
        return HttpResponse(html)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    尽管这种技术便于解释视图是如何工作的,但直接将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="现在时刻:

    %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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    模版语法重点:

    变量:{{ 变量名 }}
    	1 深度查询 用句点符
    	2 过滤器
      3 标签:{{% % }}
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    二、模版语法之变量

    在Django模版中遍历复杂数据结构的关键语句是句点字符,语法:
    {{ b变量名}}
    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='点我'
        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())
    

    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>fooul>
    
                    {% 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.namep>
                {% 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>withh3>
                {% 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 %}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130

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

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

    三、模版之过滤器

    语法

    {{ obj|filter__name:param }} 变量名|过滤器名称:值
    
    • 1

    1. default

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

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

    2. length

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

    {{ value|length }}
    
    • 1

    3. filesizeformat

    将值格式化为一个最为合适的文件尺寸(例如13KB,2GB),示例:

    {{ value|filesizeformat }}
    
    • 1

    如果 value123456789,输出将会是 117.7 MB

    4. date

    如果value = datetime.datetime.now()

    {{ vlaue|date:"Y-m-d H:i:s" }}
    
    • 1

    5. slice(切片)

    如果value = “hello world”

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

    6. truncatechars

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

    {{ value:truncatechars:9 }}
    
    • 1

    7. safe

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

    value="">点击"
    
    • 1
    
    {{ value|safe}}
    
    
    from django.utils.safestring import mark_safe
    res = mark_safe('

    HELLO WORLD

    '
    )
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    8. 其他过滤器

    过滤器描述
    upper以大写方式输出
    add给value加上一个数值
    addslashes单引号加上转义号
    capfirst第一个字母大写
    center输出指定长度的字符串,把变量居中
    cut删除指定字符串
    date格式化日期
    default如果值不存在,则使用默认值代替
    default_if_none如果值为None, 则使用默认值代替
    dictsort按某字段排序,变量必须是一个dictionary
    dictsortreversed按某字段倒序排序,变量必须是dictionary
    divisibleby判断是否可以被数字整除
    escape按HTML转义,比如将”<”转换为”<”
    filesizeformat增加数字的可读性,转换结果为13KB,89MB,3Bytes等
    first返回列表的第1个元素,变量必须是一个列表
    floatformat转换为指定精度的小数,默认保留1位小数
    get_digit从个位数开始截取指定位置的数字
    join用指定分隔符连接列表
    length返回列表中元素的个数或字符串长度
    length_is检查列表,字符串长度是否符合指定的值
    linebreaks用或标签包裹变量
    linebreaksbr用标签代替换行符
    linenumbers为变量中的每一行加上行号
    ljust输出指定长度的字符串,变量左对齐
    lower字符串变小写
    make_list将字符串转换为列表
    pluralize根据数字确定是否输出英文复数符号
    random返回列表的随机一项
    removetags删除字符串中指定的HTML标记
    rjust输出指定长度的字符串,变量右对齐
    slice切片操作, 返回列表
    slugify在字符串中留下减号和下划线,其它符号删除,空格用减号替换
    stringformat字符串格式化,语法同python
    time返回日期的时间部分
    timesince以“到现在为止过了多长时间”显示时间变量
    timeuntil以“从现在开始到时间变量”还有多长时间显示时间变量
    title每个单词首字母大写
    truncatewords将字符串转换为省略表达方式
    truncatewords_html同上,但保留其中的HTML标签
    urlencode将字符串中的特殊字符转换为url兼容表达方式
    urlize将变量字符串中的url由纯文本变为链接
    wordcount返回变量字符串中的单词数

    四、模版之标签

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

    1. for标签

    • 遍历每一个元素:
    {% for person in person_list %}
        <p>{{ person.name }}</p>
    {% endfor %}
    
    #可以利用{% for obj in list reversed %}反向完成循环。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 遍历一个字典
    {% for key,val in dic.items %}
        <p>{{ key }}:{{ val }}</p>
    {% endfor %}
    
    {% for foo in d.keys %}
        <p>{{ foo }}</p>
    {% endfor %}
    
    {% for foo in d.values %}
        <p>{{ foo }}</p>
    {% endfor %}
    
    {% for foo in d.items %}
        <p>{{ foo }}</p>
    {% endfor %}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    注:循环序号可以通过{{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         本层循环的外层循环
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    for … empty

    # for 标签带有一个可选的{% empty %} 从句,以便在给出的组是空的或者没有被找到时,可以有所操作。
    {% for person in person_list %}
        <p>{{ person.name }}</p>
    
    {% empty %}
        <p>sorry,no person here</p>
    {% endfor %}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    2. 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语句支持 andor==><!=<=>=innot inisis not判断。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    3. with

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

    d = {'username':'kevin','age':18,'info':'这个人有点意思','hobby':[111,222,333,{'info':'NB'}]}
    
    # with起别名
    {% with d.hobby.3.info as nb  %}
        <p>{{ nb }}</p>with语法内就可以通过as后面的别名快速的使用到前面非常复杂获取数据的方式
        <p>{{ d.hobby.3.info }}</p>
    {% endwith %}
    
    
    {% with total=business.employees.count %}
        {{ total }} employee{{ total|pluralize }}
    {% endwith %}
    不要写成as
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    4. csrf_token

    {% csrf_token%}
    
    • 1

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

    五、自定义标签和过滤器

    1、在settings中的INSTALLED_APPS配置当前app,不然django无法找到自定义的simple_tag.
    2、在app中创建templatetags模块(模块名只能是templatetags
    3、创建任意 .py 文件,如:my_tags.py

    from django import template
    from django.utils.safestring import mark_safe
     
    register = template.Library()   #register的名字是固定的,不可改变
     
    @register.filter
    def filter_multi(v1,v2):
        return  v1 * v2
        
    @register.simple_tag
    def simple_tag_multi(v1,v2):
        return  v1 * v2
        
    @register.simple_tag
    def my_input(id,arg):
        result = "" %(id,arg,)
        return mark_safe(result)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

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

    {%load my_tags %}
    
    • 1

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

    {% load xxx %}  
          
    # num=12
    {{ num|filter_multi:2 }} #24
     
    {{ num|filter_multi:"[22,333,4444]" }}
     
    {% simple_tag_multi 2 5 %}  参数不限,但不能放在if for语句中
    {% simple_tag_multi num 5 %}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

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

    {% if num|filter_multi:30 > 100 %}
        {{ num|filter_multi:30 }}
    {% endif %}
    
    • 1
    • 2
    • 3

    六、模版导入和继承

    模版导入

    语法:{% include '模版名称' %}
    
      如:{% include 'adv.html' %}
    
    
    • 1
    • 2
    • 3
    • 4
    <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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    <!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">
        {#    #}
        <style>
            * {
                margin: 0;
                padding: 0;
            }
    
            .header {
                height: 50px;
                width: 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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    {% extends 'base.html' %}
    
    {% block conn %}
        {{ block.super }}
    是啊
    
    {% endblock conn%}
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    模版继承
    Django模版引擎中最强大也是最复杂的部分就是模版继承了。模版继承可以让您创建一个基本的“骨架”模版,它包含您站点中的全部元素,并且可以定义能够被子模版覆盖的 blocks 。
    通过从下面这个例子开始,可以容易的理解模版继承:

    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="/">Homea>li>
                <li><a href="/blog/">Bloga>li>
            ul>
        {% endblock %}
    div>
    
    <div id="content">
        {% block content %}{% endblock %}
    div>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    这个模版,我们把它叫作 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 %}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    请注意,子模版并没有定义 `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` 标签。
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    七、静态文件相关

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

    引用JS文件时使用:

    {% load static %}
    <script src="{% static "mytest.js" %}"></script>
    
    • 1
    • 2

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

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

    使用get_static_prefix

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

    或者

    {% 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!" />
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    ** 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}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    templates/snippets/result.html

    <ul>
      {% for choice in data %}
        <li>{{ choice }}</li>
      {% endfor %}
    </ul>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
  • 相关阅读:
    手记系列之二 ----- 关于IDEA的一些使用方法经验
    wordpress添加评论过滤器
    解密JavaChassis3:易扩展的多种注册中心支持
    210. 课程表 II
    leetcode112.路径总和
    windows安装maven,配置环境变量
    vue-jest vue3
    卷积神经网络的算法过程,卷积神经网络算法实现
    ROS 机器人操作系统:版本说明
    降本增效两不误——云原生赋能航空业数字化转型
  • 原文地址:https://blog.csdn.net/qq_43710648/article/details/134423241