5,Django模板语言

 

 

只需要记两种特殊符号:

  变量相关的用{{}},

  逻辑相关的用{%%}。

一、变量

当模版系统遇到点("."),它将以这样的顺序查询:

字典查询(Dictionary lookup)
属性或方法查询(Attribute or method lookup)
数字索引查询(Numeric index lookup)

注意事项:

  1. 如果计算结果的值是可调用的,它将被无参数的调用。 调用的结果将成为模版的值。
  2. 如果使用的变量不存在, 模版系统将插入 string_if_invalid 选项的值, 它被默认设置为'' (空字符串) 。
def template_test(request):
    l = [11, 22, 33]
    d = {"name": "alex"}

    class Person(object):
        def __init__(self, name, age):
            self.name = name
            self.age = age

        def dream(self):
            return "{} is dream...".format(self.name)

    Alex = Person(name="Alex", age=34)
    Egon = Person(name="Egon", age=9000)
    Eva_J = Person(name="Eva_J", age=18)

    person_list = [Alex, Egon, Eva_J]
    return render(request, "template_test.html", {"l": l, "d": d, "person_list": person_list})
view中代码:
{% 取l中的第一个参数 %}
{{ l.0 }}
{% 取字典中key的值 %}
{{ d.name }}
{% 取对象的name属性 %}
{{ person_list.0.name }}
{% .操作只能调用不带参数的方法 %}
{{ person_list.0.dream }}
模板中支持的写法:

二、Filters(过滤器)

在Django的模板语言中,通过使用 过滤器 来改变变量的显示。

过滤器的语法: {{ value|filter_name:参数 }}

使用管道符"|"来应用过滤器。

例如:{{ name|lower }}会将name变量应用lower过滤器之后再显示它的值。lower在这里的作用是将文本全都变成小写。

注意事项:

  1. 过滤器 支持“链式”操作。即一个过滤器的输出作为另一个过滤器的输入。
  2. 过滤器 可以接受参数,例如:{{ sss|truncatewords:30 }},这将显示sss的前30个词。
  3. 过滤器 参数包含空格的话,必须用引号包裹起来。比如使用逗号和空格去连接一个列表中的元素,如:{{ list|join:', ' }}
  4. '|'左右  没有空格没有空格没有空格

2.1 内置过滤器

#如果一个变量是false或者为空,使用给定的默认值。 否则,使用变量的值。
{{ value|default:"nothing"}}
#返回值的长度,作用于字符串和列表。
{{ value|length }}
#将值格式化为一个 “人类可读的” 文件尺寸 
{{ value|filesizeformat }}
#切片
{{value|slice:"2:-1"}}
#时间格式化
{{ value|date:"Y-m-d H:i:s"}}
#告诉Django这段代码是安全的不必转义【xss攻击】
{{ value|safe}}
#截断超出的字符串,将以可翻译的省略号序列(“...”)结尾
{{ value|truncatechars:9}}
#移除 value中所有的与给出的变量相同的字符串
{{ value|cut:' ' }}
#使用字符串连接列表
{{ value|str.join(list)}}
#将日期格式设为自该日期起的时间,
{{ blog_date|timesince:comment_date }}
#测量从现在开始直到给定日期或日期时间的时间
例如,如果今天是2006年6月1日,而conference_date是保留2006年6月29日的日期实例,则{{ conference_date | timeuntil }}将返回“4周”。
{{ conference_date|timeuntil:from_date }}

2.2 自定义filter

自定义过滤器只是带有一个或两个参数的Python函数:

  • 变量(输入)的值 - -不一定是一个字符串
  • 参数的值 - 这可以有一个默认值,或完全省略
#自定义filter代码文件摆放位置:
app01/
    __init__.py
    models.py
    templatetags/        # 在app01下面新建一个package package
        __init__.py
        app01_filters.py      # 建一个存放自定义filter的文件
    views.py
# 编写自定义filter
from django import template
register = template.Library()

@register.filter(name="cut")
def cut(value, arg):
    return value.replace(arg, "")


@register.filter(name="addSB")
def add_sb(value):
    return "{} SB".format(value)
#模板语言中,使用自定义filter
{# 先导入我们自定义filter那个文件 #}
{% load app01_filters %}

{# 使用我们自定义的filter #}
{{ somevariable|cut:"0" }}
{{ d.name|addSB }}

2.3 自定义simple_tag

#和自定义filter类似,只不过接收更灵活的参数。

#定义注册simple tag
@register.simple_tag(name="plus")
def plus(a, b, c):
    return "{} + {} + {}".format(a, b, c)


#使用自定义simple tag
{% load app01_simple_tag %}

{% plus "1" "2" "abc" %}

2.4 自定义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 {"reg": data}

②templates/result.html

<ul>
  {% for choice in reg %}
    <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>

三、Tags

 1、for循环

#普通for循环
<ul>
{% for user in user_list %}
    <li>{{ user.name }}</li>
{% endfor %}
</ul>


# for ... empty
<ul>
{% for user in user_list %}
    <li>{{ user.name }}</li>
{% empty %}
    <li>空空如也</li>
{% endfor %}
</ul>
VariableDescription
forloop.counter 当前循环的索引值(从1开始)
forloop.counter0 当前循环的索引值(从0开始)
forloop.revcounter 当前循环的倒序索引值(从1开始)
forloop.revcounter0 当前循环的倒序索引值(从0开始)
forloop.first 当前循环是不是第一次循环(布尔值)
forloop.last 当前循环是不是最后一次循环(布尔值)
forloop.parentloop 本层循环的外层循环

2、if判断

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

{% if user_list %}
  用户人数:{{ user_list|length }}
{% elif black_list %}
  黑名单数:{{ black_list|length }}
{% else %}
  没有用户
{% endif %}

 3、with

定义一个中间变量,多用于给一个复杂的变量起别名。

注意等号左右不要加空格。

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

 4、csrf_token

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

在页面的form表单里面写上{% csrf_token %}

 5、注释

{# ... #}

 6、注意事项

(1)Django的模板语言不支持连续判断,即不支持以下写法:

{% if a > b > c %}
...
{% endif %}

(2) Django的模板语言中属性的优先级大于方法

def xx(request):
    d = {"a": 1, "b": 2, "c": 3, "items": "100"}
    return render(request, "xx.html", {"data": d})

如上,我们在使用render方法渲染一个页面的时候,传的字典d有一个key是items并且还有默认的 d.items() 方法,此时在模板语言中:

{{ data.items }}

默认会取d的items key的值。

四、母版

①什么时候用母版?
 html页面有重复的代码,把它们提取出来放到一个单独的html文件。(比如:导航条和左侧菜单)
② 子页面如何使用母版?
   {% extends 'base.html' %} --> 必须要放在子页面的第一行
  母版里面定义block(块),子页面使用block(块)去替换母版中同名的块

 1、母版

  通常会在母板中定义页面专用的CSS块和JS块,方便子页面替换。

<!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>Title</title>
  {% block page-css %}
  
  {% endblock %}
</head>
<body>

<h1>这是母板的标题</h1>
{% block page-main %}

{% endblock %}
<h1>母板底部内容</h1>
{% block page-js %}

{% endblock %}
</body>
</html>

 2、继承母版

  在子页面中在页面最上方使用下面的语法来继承母板。

{# 继承母版 #}
{% extends 'base.html' %}

{# 把自己页面的内容 塞到母版里面相应的位置 #}
{% block page-main %}
   <h1 class="page-header">书籍管理页面</h1>
            <div class="panel panel-primary">
                <!-- Default panel contents -->
                <div class="panel-heading">书籍列表 <i class="fa fa-thumb-tack pull-right"></i></div>
                <div class="panel-body">
                    <div class="row" style="margin-bottom: 15px">
                        <div class="col-md-4">
                            <div class="input-group">
                                <input type="text" class="form-control" placeholder="Search for...">
                                <span class="input-group-btn">
                                    <button class="btn btn-default" type="button">搜索</button>
                                </span>
                            </div><!-- /input-group -->
                        </div><!-- /.col-md-4 -->
                        <div class="col-md-3 pull-right">
                            <a href="/add_book/" class="btn btn-success pull-right">新页面添加</a>
                            <button class="btn btn-success pull-right" data-toggle="modal" data-target="#myModal">新增</button>
                        </div>

                    </div><!-- /.row -->

                    <table class="table table-bordered">
                        <thead>
                        <tr>
                            <th>#</th>
                            <th>id</th>
                            <th>书名</th>
                            <th>出版社名称</th>
                            <th>操作</th>
                        </tr>
                        </thead>
                        <tbody>
                        {% for i in all_book %}
                            <tr>
                                <td>{{ forloop.counter }}</td>
                                <td>{{ i.id }}</td>
                                <td>{{ i.title }}</td>
                                <td>{{ i.publisher.name }}</td>
                                <td>
                                    <a class="btn btn-danger" href="/delete_book/?id={{ i.id }}">删除</a>
                                    <a class="btn btn-info" href="/edit_book/?id={{ i.id }}">编辑</a>
                                </td>
                            </tr>
                        {% empty %}
                            <tr>
                                <td colspan="5" class="text-center">暂时没有数据哦~</td>
                            </tr>
                        {% endfor %}
                        </tbody>
                    </table>

                    <nav aria-label="Page navigation" class="text-right">
                        <ul class="pagination">
                            <li>
                                <a href="#" aria-label="Previous">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                            <li><a href="#">1</a></li>
                            <li><a href="#">2</a></li>
                            <li><a href="#">3</a></li>
                            <li><a href="#">4</a></li>
                            <li><a href="#">5</a></li>
                            <li>
                                <a href="#" aria-label="Next">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        </ul>
                    </nav>
                </div>

            </div>

{% endblock %}
View Code

 3、块

  通过在母板中使用{% block  xxx %}来定义"块"。

  在子页面中通过定义母板中的block名来对应替换母板中相应的内容。

{% block page-js %}
    <script src="/static/author_list_only.js"></script>


{% block page-css %}
    {% load static %}
{#  <link rel="stylesheet" href="{% static 'book_list_only.css' %}">#}
    <link rel="stylesheet" href="{% get_static_prefix %}book_list_only.css">
{% endblock %}

 4、静态文件相关

  (1){% static %}

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

  (2){% 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!" />

5、组件

可以将常用的页面内容如导航条,页尾信息等组件保存在单独的文件中,然后在需要使用的地方按如下语法导入即可。

{% include 'navbar.html' %}

 

posted @ 2020-05-09 17:18  傻白甜++  阅读(174)  评论(0编辑  收藏  举报
TOP