Django之模板语法

中文文档

1、重要语法

  {{ }}  和变量相关

  {% %} 和逻辑相关

# 使用方法:
# 试图views.py下
from django.shortcuts import render
import datetime
def current_time(request):
    user  = {"name": "sun", "age": 18}
    time = datetime.datetime.now()
    return render(request, "time.html", {"time": str(time), "user": user})
<!-- time.html 文件下-->

<h1>{{ time }}</h1>
<h1>{{ user.name }}</h1>
<h1>{{ user.age }}</h1>


<!--
结果:
2019-04-16 15:38:06.693945
sun
18
-->

2、变量的使用

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

  语法:{{变量名}}

# 后端传值的方式,2种
# views.py下
def index(request):
    dic = {1:2, "name": "sun"}

    # 第一种方式
    return render(request, "index.html",{"dic": dic})
    # 第二种方式:
    return render(request, "index.html", locals())
    # 弊端
    # 会把不需要用到的值也传到前端


# 后端传值的类型
    strings = "Hello Baby!"
    lis = [1,2,4,["a", "abc"]]
    dic = {1:2, "name": "sun"}
    se = {1,2,3,4}
    tu = (1,2,3)

  后端传值的类型

类型
视图函数下定义
传值
html内调用方式
结果
字符串
strings = "Hello Baby!"
return render(
      request,
      "time.html",
      {
            "str": strings,
            "list": lis,
            "dict": dic,
            "tuple": tu,
            "set": se,
            "foo": foo,
            "obj": obj,
      }
)
{{ str }}
Hello Baby!
列表
lis = [1,2,4,["a", "abc"]]
{{ list.0 }}
{{ list.3.1 }}
1
abc
字典
dic = {1:2, "name": "sun"}
{{ dict.name }}
sun
元组
tu = (1,2,3)
{{ tuple.2 }}
3
集合
se = {1,2,3,4}
{{ set }}
{1,2,3,4}
函数
def foo():
      return "foo函数返回值"
{{ foo }}
foo函数返回值
class Person(object):
      def __init__(self, name):
            self.name = name
 
      def study(self):
             return "%s study."%self.name
obj = Person("yw")
{{ obj }}
{{ obj.name }}
{{ obj.study }}
obj 对象的内存地址
yw
yw stude.
说明:可迭代对象都可以使用 for 循环:{% for i in 可迭代对象 %} <p>{{ i }}</p> {% endfor %}

 3、过滤器

  本质:模板中变量可以使用的函数

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

  注意:

    1. 冒号 : 左右都不能加空格

    2. 管道符 | 左右可以加空格 

  3.1 常用过滤器

    1. default 

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

{{ value | default:"nothing" }}
如果value的值是:"" [], () {}, False
结果是:nothing,
如果value的值是:"123"
结果是:123
# 内部使用的是 or

     2. length

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

{{ value | length }}
value = [1,2,4,3]
结果是; 4
内部调用的是len()函数,如果数据类型不符,则返回0

    3. filesizeformat

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

{{ value|filesizeformat }}
value = 1024
结果是:1.0 KB
value = 12342234
结果是:11.8 MB

    4. date 

      格式化日期

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

# views.py 下
value=datetime.datetime.now()
结果是: 2019-04-16

    5. slice

value = "Hello Baby!"
{{ value|slice:"2:-1" }}
结果是:llo Baby
{{ value|slice:"2:-1:2" }}
结果是:lBb
{{ value|slice:"::-1" }}
结果是:!ybaB olleH
内部使用的是slice函数,slice()函数创造一个切片规则对象

    6. truncatechars和truncatewords

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

{{ value|truncatechars:6 }}
value = "abcdefgh"
结果是:abc...  # 包括省略号在内6个字符

{{ value|truncatewords:3 }}
Value = "Quasimodo lost his beloved girl and in the end his cherished belfry."
结果是:Quasimodo lost his... # 不包括省略号,以空格为单位拆分

    7. safe

      Django的模板中会对HTML标签和JS等语法标签进行自动转义,转义一个普通的字符串,safe告诉django不要转义

{{ value|safe}}
value="<a href="">点击</a>"
结果直接再前端显示一个a标签

# 后端也可以告诉django不要转义
from django.utils.safestring import mark_safe
    s1 = mark_safe("<h1>我是h1</h1>")
    s2 = mark_safe("<script>alert(123)</script>")
然后把s1 和s2返回给前端

4、标签

  4.1 for标签

<!-- 遍历一个列表 -->
{% for person in person_list %}
    <p>{{ person }}</p>
{% endfor %}

{% for obj in list reversed %}反向完成循环

<!-- 遍历一个字典 -->
{% for key in dic %}
    <p>{{ key }}:{{ dic.key }}</p>
{% endfor %}
<!--
字典还有其它方法:
dic.keys
dic.values
dc.items
-->
循环中,其它的属性
forloop.counter     取当前索引值(从1开始)
forloop.counter     取当前索引值(从0开始)
forloop.revcounter   当前循环的倒序索引值(从1开始)
forloop.revcounter0  当前循环的倒序索引值(从0开始)
forloop.first   当前循环是不是第一次循环(布尔值)
forloop.last    当前循环是不是最后一次循环(布尔值)
forloop.parentloop         本层循环的外层循环

  4.2 for ... empty 标签

    给出的组是空的或者没有被找到时,可以有所操作

{% for i in list%}
    <p>{{ i }}</p>

{% empty %}
    <p>sorry,no person here</p>
{% endfor %}

  4.3 if 标签

{% if num > 100 or num < 0 %}
    <p>vain.</p>
{% elif num > 80 and num < 100 %}
    <p>better.</p>
{% else %}
    <p>good.</p>
{% endif %}

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

  4.4 with标签

    使用一个简单地名字缓存一个复杂的变量

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

早期的格式:
 {% with business.employees.count as total %}

  4.5 csrf_token 标签

    {% csrf_token%}

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

5、自定义tag, filter, inclusion_tag

  5.1 前期文件创建

    1. 必须在app应用下创建一个文件夹必须是:templatetags

    2. 随便创建一个文件my_tag.py

    3. 文件my_tag.py 下

      from django import template

      register = template.Library()

  5.2 自定义过滤器

@register.filter(name='multi')
def do_multi(a,b):
    return a * b

调用:
{% load my_tag %}
{{  12 | multi  10  }}
结果:120

  5.3 自定义标签

@register.simple_tag(name='join')
def do_join(a,b,c, type=None):
    return (type).join([a,b,c])

调用:
{% load my_tag %}
{% join 'abc', "ab", "a", "-" %}
结果:abc-ab-a

  5.4 自定义inclusion_tag

@register.inclusion_tag('xxx.html')
def get_html(n):
    l = []
    for i in range(n):
        l.append('第%s项'%i)
    return {'l':lis}

# xxx.html 文件
<ul>
    {% for foo in lis %} 
        <li>{{ foo }}</li>
    {% endfor %}
</ul>

# index.html
调用:
{% load my_tag %}
{% get_html 5 %} 结果: <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul>

6、文件的导入和继承

  6.1 导入

    语法:{% include '模版名称' %}

demo.html
<h1>Quasimodo lost his beloved girl and in the end his cherished belfry.</h1>

base.html
<div>
{% include "demo.html" %}
{% include "demo.html" %}
</div>

结果:
Quasimodo lost his beloved girl and in the end his cherished belfry.
Quasimodo lost his beloved girl and in the end his cherished belfry.

  6.2 继承

    母版base.html语法:

      {% block content %}

      {% endblock %}

    子板继承:

      {% extends "base.html" %}

      {% block content %}

      {% endblock %}

<!-- base.html -->
<!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>
<!-- 子模版 -->
{% 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. {% extends %} 标签,它必须是模版中的第一个标签

    2. 在base模版中设置越多的 {% block %} 标签越好。但子模版不必定义全部继承。

    3. 为了更好的可读性,你也可以给你的 {% endblock %} 标签一个 名字。

      {% block content %}

      {% endblock content %}

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

    5. {{ block.super }} 可以调用base.html 的{% block %}内的内容 

 

posted @ 2019-04-17 21:03  yw_sun  阅读(105)  评论(0)    收藏  举报