Detailed introduction to Django template language (with code)

不言
Release: 2018-10-10 16:31:38
forward
3128 people have browsed it

This article brings you a detailed introduction to the Django template language (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Common syntax

{{ }} and {% %}

Use {{}} for variables related, and {% %} for logic related ones

Variables

Use this syntax in Django’s template language: {{ variable name}}.

When the template engine encounters a variable, it will evaluate the variable and replace itself with the result.

The naming of variables includes any combination of letters, numbers and underscores ("_") (numbers starting with are not recommended).

There cannot be spaces or punctuation marks in variable names.

The dot (.) has a special meaning in template languages.

When the template system encounters a dot ("."), it will query in this order:

Dictionary lookup
Attribute or method lookup )
Numeric index lookup

##Note:

1. If there are attributes or methods with the same name when querying, the query will be prioritized in the above order.

2. If the value of the calculation result is callable (passing parameters), it will be ignored. Parameters are called (without parentheses). The result of the call will become the value of the template.

3. If the variable used does not exist, the template system will insert the value of the string_if_invalid option, which is set to "" by default ( Empty string).

Code in views:

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})
Copy after login

Supported writing methods in template


{# 取l中的第一个参数 #}
{{ l.0 }}
{# 取字典中key的值 #}
{{ d.name }}
{# 取对象的name属性 #}
{{ person_list.0.name }}
{# .操作只能调用不带参数的方法 #}
{{ person_list.0.dream }}
Copy after login


Filters:

In Django’s template language, use filters to change the display of variables.

Filter syntax: {{ value|filter_name:parameter }}

Use the pipe character "|" to apply the filter.

For example: {{ name|lower }} will apply the lower filter to the name variable and then display its value. The function of lower here is to turn all text into lowercase.

Notes:

1. Filter supports "chain" operation. That is, the output of one filter serves as the input of another filter.

2. The filter can accept parameters, for example: {{ sss|truncatewords:30 }}, which will display the first 30 words of sss. (The parameter can only be one or none)

3. If the filter parameter contains spaces, it must be wrapped in quotation marks. For example, use commas and spaces to connect elements in a list, such as: {{ list|join:', ' }}

4. There are no spaces around '|' and ':'.

Django template language provides about 60 built-in filters

default

If a variable is false or empty, use the given default value, otherwise, use The value of the variable.


{{ value|default:'nothing'}}
Copy after login


Note:

OPTIONS of TEMPLATES can add an option: string_if_invalid: 'Cannot find To ', if the value value is not uploaded, the invalid one can replace the default function

length Returns the length of the value, applies to strings and lists

{{value|length}} Returns the value Length, such as value=['a','b','c','d'], it will display 4


filesizeformat Format the value into a 'human readable' file Scale (for example: '13 kb', '4.2 MB', etc.)

{{value|filesizeformat}} If value is 123456789, the output will be 117.7MB.

add Add to the variable Parameter

{{value|add:'2'}} If value is the number 1, the output result is 3

{{first|add:second}} If first is [1, 2,3], second is [4,5,6], the result is: [1,2,3,4,5,6]

ljust Left-aligned

''{{value|ljust:'10'}}''
Copy after login

rjust Rjust-aligned

"{{value|rjust:'10'}}"
Copy after login

center center

"{{value|center:'15'}}"
Copy after login

slice slice

{{value|slice:'2:-1'}}
Copy after login

date formatting

{{value|date:'Y-m-d H:i:s'}}
Copy after login

##safe

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

(Django模块中有自己的安全机制,不是你写什么就按照原代码执行,比如危险代码,违规内容等,加上|safe 过滤器,会让你的代码按照原有的意思执行,解除安全机制.)

比如:  

value = &#39;<a href=#>点我</a>&#39;
Copy after login

{{values|safe}}

truncatechars

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

参数: 截断的字符串

{{values|truncatechars:9}}

注意: 连在一起意为一个单词,空格隔开则表示另一个单词.比如把标点符号和单词连一起,则表示一个单词.

truncatewords

在一定数量的字后截断字符串

{{value|truncatewords:9}}

cut  移除value中所有的与给出的变量相同的字符串

{{value|cut:' '}} (如果value为'da sha bi',那么将输出为"dashabi")

join  使用字符串连接列表,例如Python的str.join(list)

timesince 将日期格式设为该日期起的时间

采用一个可选参数,它是一个包含用作比较点的日期的变量(不带参数,比较点为现在)。 例如,如果blog_date是表示2006年6月1日午夜的日期实例,并且comment_date是2006年6月1日08:00的日期实例,则以下将返回“8小时”:

{{conference_date|timeuntil:from_date}}

自定义filter

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

变量(输入) 的值 不一定是一个字符串

参数的值 这可以有一个默认值,或完全省略

例如, 在过滤器{{var|foo:'bar'}}中,过滤器foo将传递变量var和变量'bar'.

自定义filter代码文件摆放位置:

app01/
    __init__.py
    models.py
    templatetags/  # 在app01下面新建一个package package,文件名字必须是templatetags
        __init__.py
        app01_filters.py  # 建一个存放自定义filter的文件,文件名自定义
    views.py
Copy after login

编写自定义filter

from django import template
# 固定写法,生成一个注册实例对象
register = template.Library()
#以上为固定写法,不能随意改变
@register.filter(name="cut")  # 告诉Django模板语言我现在注册一个自定义的filter.
def cut(value, arg):      # 第一个参数为变量,第二个参数可以没有,是过滤器参数
    return value.replace(arg, "") 
@register.filter(name="addSB")# 若括号内有name,则表示过滤器名称改变为name后的名字
def add_sb(value):
    return "{} SB".format(value)  # 引用该过滤器就会把value值后面加上SB
Copy after login

使用自定义filter

{# 先导入我们自定义filter那个文件 #}
{% load app01_filters %}
{# 使用我们自定义的filter #}
{{ somevariable|cut:"0" }}
{{ d.name|addSB }}
Copy after login

自定义filter步骤
定义:
1. 在app目录下创建一个名为 templatetags 的python包
2. 在上面创建的包内部创建一个python文件: ooxx.py
3. 在ooxx.py文件中按照固定的格式注册的一个自定义的filter
from django import template

# 固定写法,生成一个注册实例对象
register = template.Library()
@register.filter()  # 告诉Django的模板语言我现在注册一个自定义的filter
def add_sb(value):
"""
给任意指定的变量添加sb
:param value: |左边被修饰的那个变量
:return: 修饰后的变量内容
"""
return value + &#39;sb&#39;
Copy after login
@register.filter()
def add_str(value, arg):
return value + arg
Copy after login

使用:
1. 重启Django项目
2. 在HTML页面中:{% load python文件名 %}
3. {{ name|add_str:'大好人' }}

Tags

for

<ul>
{% for user in user_list %}    
<li>{{forloop.counter}}-{{ user.name }}</li>
{% endfor %}
</ul>
Copy after login

for循环可用的一些参数:

 

注意:本层循环的外层循环即是父层循环,上一层循环.

for empty 当for 后面的条件不成立时执行empty后面的程序

<ul>
{% for user in user_list %}
    <li>{{ user.name }}</li>
{% empty %}
    <li>空空如也</li>
{% endfor %}
</ul>
Copy after login

if , elif 和 else

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

当然也可以只有if和else

{% if user_list|length > 5 %}
  七座豪华SUV
{% else %}
    黄包车
{% endif %}
Copy after login

注意: if语句支持and, or, ==, >,<, !=, <=, >=, in, not in, is not 判断不支持 算术运算.(+, -, *, /)

with:定义一个中间变量

{% with total=business.employees.count %}  
# 把business.employee.count用total表示
    {{ total }} employee{{ total|pluralize }}
{% endwith %}
Copy after login

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

在页面的form表单里写上{%csrf_token%}即可通过,会自动生成一串验证码(64个).

(传说中46行注释,可以取消注释,)

注释  {# ... #}

注意事项

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

{% if a>b>c %}
...
{% endif %}
Copy after login

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

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

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

{{ data.items }}默认会取d的items key的值

母版

<!DOCTYPE html>
<html>
<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块,可以在子页中写出相对应的块的名称,表示操作该块,并替换掉母板中的对应块里的内容.-->
{% block page-main %}
{% endblock %}
 <h1>母板底部内容</h1>

{% block page-js %}
{% endblock %}
</body>
</html>
Copy after login

注意: 我们通常会在母板中定义页面专用的css块和js块,方便子页面替换.

继承母板

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

{% extends 'layouts.html' %}

块(block)

通过在母板中使用{% block ×××%}来定义'块'.

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

{% block page-main %}  <p>世情薄</p>
  <p>人情恶</p>
  <p>雨送黄昏花易落</p>{% endblock %}
Copy after login

注意:

{% extends 'base.html' %}要写在子页面第一行(子页面代码的最前面)

{% extends ''name'' %} name 写继承的母板的名字要是字符串形式,若不加 ' ' 则表示变量自定义的内容要写在block中

组件

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

{% include 'navbar.html' %}

(直接创建一个html文件,把常用的内容粘贴即可,'' 内填写文件名称,如有必要也要把路径写上)


静态相关文件

Django项目中,路径前的static并不是文件名字,而是setting文件中的 " STATIC_URL = '/static/' "

# 能够动态地拼接路径,比如当&#39;STATIC_URL = &#39;/static/&#39;&#39;中的static改变时,就需要把以前文件中
已经写死了的static全部改变,但是如果能动态地拼接就不需要如此麻烦.

{% load static %}
<img src=&#39;{% static &#39;image/hi.jpg&#39; %}&#39; alt=&#39;Hi!&#39; />



#引用JS文件时使用:

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



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

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

使用 get_static_prefix

表示拿到static这一别名

使用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!" />
Copy after login

自定义simpletag

和自定义filter类似,只不过接受更灵活的参数(可以接受若干参数).

定义注册 simple tag

@register.simple_tag(name="plus")def plus(a, b, c):    
return "{} + {} + {}".format(a, b, c)
Copy after login

使用自定义 simple tag

{% load app01_demo %}
{# simple tag #}{% plus "1" "2" "abc" %}
Copy after login

inclusion_tag 多用于返回html代码片段

示例: templatetags/my_inclusion.pyfrom django import template

register = template.Library()
# 以上固定写法
@register.inclusion_tag(&#39;result.html&#39;)  # 括号内为文件名
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} # 字典内传给代码段的参数,必须是可迭代的
Copy after login

templates/result.html

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

templates/index.heml

<!DOCTYPE html>
<html>
<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 my_inclusion %}

{% show_results 10 %} # 参数是10
</body>
</html>
Copy after login

The above is the detailed content of Detailed introduction to Django template language (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!