内置模板标签和过滤器

内置模板标签和过滤器

本文档描述了 Django 内置的模板标签和过滤器。如果有的话,建议你使用 自动化文档,因为它也会包含安装的任何自定义标签或过滤器的文档。

内置标签参考

autoescape

控制当前的自动转义行为。该标签以 on 或 off 作为参数,决定块内是否有自动转义行为。此区块以 endautoescape 结束标签关闭。

Sample usage:

{% autoescape on %}
    {{ body }}
{% endautoescape %}

When auto-escaping is in effect, all content derived from variables has HTML escaping applied before placing the result into the output (but after any filters are applied). This is equivalent to manually applying the escape filter to each variable.

The only exceptions are variables already marked as “safe” from escaping. Variables could be marked as “safe” by the code which populated the variable, by applying the safe or escape filters, or because it’s the result of a previous filter that marked the string as “safe”.

Within the scope of disabled auto-escaping, chaining filters, including escape, may cause unexpected (but documented) results such as the following:

{% autoescape off %}
    {{ my_list|join:", "|escape }}
{% endautoescape %}

The above code will output the joined elements of my_list unescaped. This is because the filter chaining sequence executes first join on my_list (without applying escaping to each item since autoescape is off), marking the result as safe. Subsequently, this safe result will be fed to escape filter, which does not apply a second round of escaping.

In order to properly escape every element in a sequence, use the escapeseq filter:

{% autoescape off %}
    {{ my_list|escapeseq|join:", " }}
{% endautoescape %}

block

定义一个可以被子模板覆盖的块。更多信息请参见 模板继承。

comment

忽略 {% comment %} 和 {% endcomment %} 之间的所有内容。可以在第一个标签中插入一个可选的注释。例如,这在注释代码时很有用,可以记录代码被禁用的原因。

Sample usage:

<p>Rendered text with {{ pub_date|date:"c" }}</p>
{% comment "Optional note" %}
    <p>Commented out text with {{ create_date|date:"c" }}</p>
{% endcomment %}

comment 标签不能嵌套。

csrf_token

这个标签用于 CSRF 保护,如 跨站点请求伪造 的文档中所述。

cycle

每次遇到这个标记时,都会产生一个参数。第一次遇到时产生第一个参数,第二次遇到时产生第二个参数,以此类推。一旦用尽所有参数,标签就会循环到第一个参数,并再次生成它。

This tag is particularly useful in a loop:

{% for o in some_list %}
    <tr class="{% cycle 'row1' 'row2' %}">
        ...
    </tr>
{% endfor %}

第一次迭代产生的 HTML 引用类 row1,第二次引用 row2,第三次再引用 row1,以此类推,每次循环迭代。

You can use variables, too. For example, if you have two template variables, rowvalue1 and rowvalue2, you can alternate between their values like this:

{% for o in some_list %}
    <tr class="{% cycle rowvalue1 rowvalue2 %}">
        ...
    </tr>
{% endfor %}

Variables included in the cycle will be escaped. You can disable auto-escaping with:

{% for o in some_list %}
    <tr class="{% autoescape off %}{% cycle rowvalue1 rowvalue2 %}{% endautoescape %}">
        ...
    </tr>
{% endfor %}

You can mix variables and strings:

{% for o in some_list %}
    <tr class="{% cycle 'row1' rowvalue2 'row3' %}">
        ...
    </tr>
{% endfor %}

In some cases you might want to refer to the current value of a cycle without advancing to the next value. To do this, give the {% cycle %} tag a name, using “as”, like this:

{% cycle 'row1' 'row2' as rowcolors %}

From then on, you can insert the current value of the cycle wherever you’d like in your template by referencing the cycle name as a context variable. If you want to move the cycle to the next value independently of the original cycle tag, you can use another cycle tag and specify the name of the variable. So, the following template:

<tr>
    <td class="{% cycle 'row1' 'row2' as rowcolors %}">...</td>
    <td class="{{ rowcolors }}">...</td>
</tr>
<tr>
    <td class="{% cycle rowcolors %}">...</td>
    <td class="{{ rowcolors }}">...</td>
</tr>

would output:

<tr>
    <td class="row1">...</td>
    <td class="row1">...</td>
</tr>
<tr>
    <td class="row2">...</td>
    <td class="row2">...</td>
</tr>

你可以在一个 cycle 标签中使用任意数量的值,用空格隔开。用单引号(')或双引号(")括起来的值被视为字符串字面,而没有引号的值被视为模板变量。

By default, when you use the as keyword with the cycle tag, the usage of {% cycle %} that initiates the cycle will itself produce the first value in the cycle. This could be a problem if you want to use the value in a nested loop or an included template. If you only want to declare the cycle but not produce the first value, you can add a silent keyword as the last keyword in the tag. For example:

{% for obj in some_list %}
    {% cycle 'row1' 'row2' as rowcolors silent %}
    <tr class="{{ rowcolors }}">{% include "subtemplate.html" %}</tr>
{% endfor %}

这将输出一个 <tr> 元素的列表,其 class 在 row1 和 row2 之间交替出现。子模板在其上下文中可以访问 rowcolors,其值将与包围它的 <tr> 的类相匹配。如果省略 silent 关键字,row1 和 row2 将作为普通文本在 <tr> 元素之外发出。

When the silent keyword is used on a cycle definition, the silence automatically applies to all subsequent uses of that specific cycle tag. The following template would output nothing , even though the second call to {% cycle %} doesn’t specify silent:

{% cycle 'row1' 'row2' as rowcolors silent %}
{% cycle rowcolors %}

你可以使用 resetcycle 标签使 {% cycle %} 标签在下次遇到时从第一个值重新开始。

debug

Outputs a whole load of debugging information, including the current context and imported modules. {% debug %} outputs nothing when the DEBUG setting is False.

Changed in Django 2.2.27:

In older versions, debugging information was displayed when the DEBUG setting was False.

extends

表示该模板扩展了一个父模板。

这个标签有两种使用方式:

  • {% extends "base.html" %} (带引号)使用字面值 "base.html" 作为要扩展的父模板的名称。
  • {% extends variable %} 使用 variable 的值。如果变量的值是一个字符串,Django 将使用这个字符串作为父模板的名称。如果变量的值是一个 Template 对象,Django 将使用该对象作为父模板。

更多内容请参见 模板继承 文档.

Normally the template name is relative to the template loader’s root directory. A string argument may also be a relative path starting with ./ or ../. For example, assume the following directory structure:

dir1/
    template.html
    base2.html
    my/
        base3.html
base1.html

In template.html, the following paths would be valid:

{% extends "./base2.html" %}
{% extends "../base1.html" %}
{% extends "./my/base3.html" %}

filter

通过一个或多个过滤器过滤块的内容。可以用管道指定多个过滤器,过滤器可以有参数,就像变量语法一样。

请注意,该块包括 filter 和 endfilter 标签之间的 所有 文本。

Sample usage:

{% filter force_escape|lower %}
    This text will be HTML-escaped, and will appear in all lowercase.
{% endfilter %}

备注

escape 和 safe 过滤器是不可接受的参数。取而代之的是,使用 autoescape 标签来管理模板代码块的自动转义。

firstof

输出第一个不是 false 的参数变量(即存在、不为空、不是一个错误的布尔值,也不是一个零的数值)。如果所有传递的变量都是 false,则不输出任何内容。

Sample usage:

{% firstof var1 var2 var3 %}

This is equivalent to:

{% if var1 %}
    {{ var1 }}
{% elif var2 %}
    {{ var2 }}
{% elif var3 %}
    {{ var3 }}
{% endif %}

You can also use a literal string as a fallback value in case all passed variables are False:

{% firstof var1 var2 var3 "fallback value" %}

This tag auto-escapes variable values. You can disable auto-escaping with:

{% autoescape off %}
    {% firstof var1 var2 var3 "<strong>fallback value</strong>" %}
{% endautoescape %}

Or if only some variables should be escaped, you can use:

{% firstof var1 var2|safe var3 "<strong>fallback value</strong>"|safe %}

你可以使用 {% firstof var1 var2 var3 as value %} 的语法将输出结果存储在一个变量中。

for

Loops over each item in an array, making the item available in a context variable. For example, to display a list of athletes provided in athlete_list:

<ul>
{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% endfor %}
</ul>

你可以通过使用 {% for obj in list reversed %} 来反向循环一个列表。

If you need to loop over a list of lists, you can unpack the values in each sublist into individual variables. For example, if your context contains a list of (x,y) coordinates called points, you could use the following to output the list of points:

{% for x, y in points %}
    There is a point at {{ x }},{{ y }}
{% endfor %}

This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data, the following would display the keys and values of the dictionary:

{% for key, value in data.items %}
    {{ key }}: {{ value }}
{% endfor %}

请记住,对于点运算符来说,字典键查询优先于方法查询。因此,如果 data 字典中包含一个名为 'items' 的键,data.items 将返回 data['items'] 而不是data.items()。如果你想在模板中使用这些方法,避免添加像字典方法一样命名的键(items、values、keys` 等)。在 模板变量的文档 中阅读更多关于点运算符的查找顺序。

for 循环设置了一组可以在循环体内直接使用的变量:

变量名 描述
forloop.counter 循环计数器,表示当前循环的索引(从 1 开始)。
forloop.counter0 循环计数器,表示当前循环的索引(从 0 开始)。
forloop.revcounter 反向循环计数器(以最后一次循环为 1,反向计数)。
forloop.revcounter0 反向循环计数器(以最后一次循环为 0,反向计数)。
forloop.first 当前循环为首个循环时,该变量为 True
forloop.last 当前循环为最后一个循环时,该变量为 True
forloop.parentloop 在嵌套循环中,指向当前循环的上级循环

for … empty

The for tag can take an optional {% empty %} clause whose text is displayed if the given array is empty or could not be found:

<ul>
{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% empty %}
    <li>Sorry, no athletes in this list.</li>
{% endfor %}
</ul>

The above is equivalent to — but shorter, cleaner, and possibly faster than — the following:

<ul>
  {% if athlete_list %}
    {% for athlete in athlete_list %}
      <li>{{ athlete.name }}</li>
    {% endfor %}
  {% else %}
    <li>Sorry, no athletes in this list.</li>
  {% endif %}
</ul>

if

The {% if %} tag evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output:

{% if athlete_list %}
    Number of athletes: {{ athlete_list|length }}
{% elif athlete_in_locker_room_list %}
    Athletes should be out of the locker room soon!
{% else %}
    No athletes.
{% endif %}

在上面的例子中, 如果 athlete_list 不是空的, 那么变量 {{ athlete_list|length }} 就会被显示出来.

正如你所看到的,if 标签可能带有一个或多个 {% elif %} 分支,以及一个 {% else %} 分支。当 {% else %} 之前的所有分支条件都不满足时,{% else %} 分支的内容会被显示出来。所有的分支都是可选的。

布尔操作

if tags may use and, or or not to test a number of variables or to negate a given variable:

{% if athlete_list and coach_list %}
    Both athletes and coaches are available.
{% endif %}

{% if not athlete_list %}
    There are no athletes.
{% endif %}

{% if athlete_list or coach_list %}
    There are some athletes or some coaches.
{% endif %}

{% if not athlete_list or coach_list %}
    There are no athletes or there are some coaches.
{% endif %}

{% if athlete_list and not coach_list %}
    There are some athletes and absolutely no coaches.
{% endif %}

Use of both and and or clauses within the same tag is allowed, with and having higher precedence than or e.g.:

{% if athlete_list and coach_list or cheerleader_list %}

将被解释为:

if (athlete_list and coach_list) or cheerleader_list

在 if 标签中使用实际的括号是无效的语法。如果需要小括号来表示优先级,应使用嵌套的 if 标签。

if 标签也可以使用运算符 ==、!=、<、>、<=、>=、in、not in、is 和 `is not,其作用如下:

== 运算符

Equality. Example:

{% if somevar == "x" %}
  This appears if variable somevar equals the string "x"
{% endif %}
!= 运算符

Inequality. Example:

{% if somevar != "x" %}
  This appears if variable somevar does not equal the string "x",
  or if somevar is not found in the context
{% endif %}
< 运算符

Less than. Example:

{% if somevar < 100 %}
  This appears if variable somevar is less than 100.
{% endif %}
> 运算符

Greater than. Example:

{% if somevar > 0 %}
  This appears if variable somevar is greater than 0.
{% endif %}
<= 运算符

Less than or equal to. Example:

{% if somevar <= 100 %}
  This appears if variable somevar is less than 100 or equal to 100.
{% endif %}
>= 运算符

Greater than or equal to. Example:

{% if somevar >= 1 %}
  This appears if variable somevar is greater than 1 or equal to 1.
{% endif %}
in 运算符

Contained within. This operator is supported by many Python containers to test whether the given value is in the container. The following are some examples of how x in y will be interpreted:

{% if "bc" in "abcdef" %}
  This appears since "bc" is a substring of "abcdef"
{% endif %}

{% if "hello" in greetings %}
  If greetings is a list or set, one element of which is the string
  "hello", this will appear.
{% endif %}

{% if user in users %}
  If users is a QuerySet, this will appear if user is an
  instance that belongs to the QuerySet.
{% endif %}
not in 操作符

不包含在其中。这是 in 运算符的取反。

is 运算符

Object identity. Tests if two values are the same object. Example:

{% if somevar is True %}
  This appears if and only if somevar is True.
{% endif %}

{% if somevar is None %}
  This appears if somevar is None, or if somevar is not found in the context.
{% endif %}
is not 运算符

Negated object identity. Tests if two values are not the same object. This is the negation of the is operator. Example:

{% if somevar is not True %}
  This appears if somevar is not True, or if somevar is not found in the
  context.
{% endif %}

{% if somevar is not None %}
  This appears if and only if somevar is not None.
{% endif %}

过滤器

You can also use filters in the if expression. For example:

{% if messages|length >= 100 %}
   You have lots of messages today!
{% endif %}

复合表达式

以上所有内容都可以组合成复合表达式。对于这样的表达式,了解表达式计算时运算符的分组方式——也就是优先规则,可能很重要。运算符的优先级,从低到高,如下所示:

  • or
  • and
  • not
  • in
  • ==、!=、<、>、<=、>=

(This follows Python exactly). So, for example, the following complex if tag:

{% if a == b or c == d and e %}

…将被解释为:

(a == b) or ((c == d) and e)

如果你需要不同的优先级,你需要使用嵌套的 if 标签。有时,为了不了解优先规则的人,这样做还是比较清楚的。

The comparison operators cannot be ‘chained’ like in Python or in mathematical notation. For example, instead of using:

{% if a > b > c %}  (WRONG)

you should use:

{% if a > b and b > c %}

ifchanged

检查一个值是否在循环的最后一次迭代中发生了变化。

{% ifchanged %} 块标签用于循环中。它有两种可能的用法。

  1. Checks its own rendered contents against its previous state and only displays the content if it has changed. For example, this displays a list of days, only displaying the month if it changes:
<h1>Archive for {{ year }}</h1>

{% for date in days %}
    {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
    <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
{% endfor %}
  1. If given one or more variables, check whether any variable has changed. For example, the following shows the date every time it changes, while showing the hour if either the hour or the date has changed:
{% for date in days %}
    {% ifchanged date.date %} {{ date.date }} {% endifchanged %}
    {% ifchanged date.hour date.date %}
        {{ date.hour }}
    {% endifchanged %}
{% endfor %}

The ifchanged tag can also take an optional {% else %} clause that will be displayed if the value has not changed:

{% for match in matches %}
    <div style="background-color:
        {% ifchanged match.ballot_id %}
            {% cycle "red" "blue" %}
        {% else %}
            gray
        {% endifchanged %}
    ">{{ match }}</div>
{% endfor %}

include

加载一个模板,并在当前上下文中进行渲染。这是一种在模板中 “包含” 其他模板的方式。

模板名称可以是一个变量,也可以是一个硬编码(引号)字符串,可以是单引号或双引号。

This example includes the contents of the template "foo/bar.html":

{% include "foo/bar.html" %}

通常模板名称是相对于模板加载器的根目录而言的。字符串参数也可以是以 ./ 或 ../ 开头的相对路径,如 extends 标签所述。

This example includes the contents of the template whose name is contained in the variable template_name:

{% include template_name %}

变量也可以是任何有 render() 方法并接受上下文的对象。这允许你在你的上下文中引用一个编译的 Template。

此外,该变量可以是模板名称的迭代,在这种情况下,将使用第一个可以加载的模板,如 select_template()。

一个被包含的模板会在包含它的模板的上下文中呈现。这个例子产生的输出是 "Hello, John!"。

  • 上下文:变量 person 设置为 "John",变量 greeting 设置为 "Hello"。

  • Template:

{% include "name_snippet.html" %}
  • The name_snippet.html template:
{{ greeting }}, {{ person|default:"friend" }}!

You can pass additional context to the template using keyword arguments:

{% include "name_snippet.html" with person="Jane" greeting="Hello" %}

If you want to render the context only with the variables provided (or even no variables at all), use the only option. No other variables are available to the included template:

{% include "name_snippet.html" with greeting="Hi" only %}

备注

include 标签应被视为 “渲染这个子模板并包含 HTML” 的实现,而不是 “解析这个子模板并包含其内容,就像它是父模板的一部分一样”。这意味着,包含的模板之间没有共享状态——每个包含都是一个完全独立的渲染过程。

块在被包含之前会被执行。这意味着一个包含了另一个模板块的模板将包含 已经被执行和渲染 的块,而不是可以被覆盖的块,例如,一个扩展模板。

load

加载一个自定义模板标签集。

For example, the following template would load all the tags and filters registered in somelibrary and otherlibrary located in package package:

{% load somelibrary package.otherlibrary %}

You can also selectively load individual filters or tags from a library, using the from argument. In this example, the template tags/filters named foo and bar will be loaded from somelibrary:

{% load foo bar from somelibrary %}

更多信息请参见 自定义标签和过滤器库。

lorem

显示随机的 “经验之谈” 拉丁文文本。这对于在模板中提供样本数据很有用。

用法:

{% lorem [count] [method] [random] %}

{% lorem %} 标签可以使用零、一、二或三个参数。这些参数是:

参数 描述
count 一个数字(或变量),包含要生成的段落或字数(默认为 1)。
method 字词为 w,HTML 段落为 p,纯文本段落块为 b (默认为 b)。
random random 一词,如果给定,在生成文本时不使用普通段落(“Lorem ipsum dolor sit amet.”)。

举例:

  • {% lorem %} 将输出常见的 “经验之谈” 段落。
  • {% lorem 3 p %} 将输出普通的 “经验之谈” 段落和两个随机段落,每个段落用 HTML <p> 标签包装。
  • {% lorem 2 w random %} 将随机输出两个拉丁语单词。

now

显示当前日期和/或时间,根据给定的字符串使用格式。这些字符串可以包含格式指定符,如 date 过滤器部分所述。

Example:

It is {% now "jS F Y H:i" %}

Note that you can backslash-escape a format string if you want to use the “raw” value. In this example, both “o” and “f” are backslash-escaped, because otherwise each is a format string that displays the year and the time, respectively:

It is the {% now "jS \o\f F" %}

这样就会显示为 “It is the 4th of September”。

备注

The format passed can also be one of the predefined ones DATE_FORMAT, DATETIME_FORMAT, SHORT_DATE_FORMAT or SHORT_DATETIME_FORMAT. The predefined formats may vary depending on the current locale and if 本地格式化 is enabled, e.g.:

It is {% now "SHORT_DATETIME_FORMAT" %}

You can also use the syntax {% now "Y" as current_year %} to store the output (as a string) inside a variable. This is useful if you want to use {% now %} inside a template tag like blocktranslate for example:

{% now "Y" as current_year %}
{% blocktranslate %}Copyright {{ current_year }}{% endblocktranslate %}

regroup

通过一个共同的属性将一个相似的对象列表重新分组。

这个复杂的标签通过一个例子得到了最好的说明:假设 cities 是一个由包含 "name"、"population" 和 "country" 键的字典所代表的城市列表。

cities = [
    {"name": "Mumbai", "population": "19,000,000", "country": "India"},
    {"name": "Calcutta", "population": "15,000,000", "country": "India"},
    {"name": "New York", "population": "20,000,000", "country": "USA"},
    {"name": "Chicago", "population": "7,000,000", "country": "USA"},
    {"name": "Tokyo", "population": "33,000,000", "country": "Japan"},
]

…而你想显示一个按国家排序的分层列表,像这样:

  • India
    • Mumbai: 19,000,000
    • Calcutta: 15,000,000
  • USA
    • New York: 20,000,000
    • Chicago: 7,000,000
  • Japan
    • Tokyo: 33,000,000

You can use the {% regroup %} tag to group the list of cities by country. The following snippet of template code would accomplish this:

{% regroup cities by country as country_list %}

<ul>
{% for country in country_list %}
    <li>{{ country.grouper }}
    <ul>
        {% for city in country.list %}
          <li>{{ city.name }}: {{ city.population }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>

让我们来看看这个例子。{% regroup %} 需要三个参数:要重新分组的列表、要分组的属性和结果列表的名称。在这里,我们通过 country 属性对 cities 列表进行重新分组,并将结果称为 country_list。

{% regroup %} 产生一个 组对象 的列表(在本例中为 country_list)。组对象是 namedtuple() 的实例,有两个字段。

  • grouper —— 被分组的项目(例如,“India” 或 “Japan” 等字符串)。
  • list —— 本组所有项目的清单(例如,country=’India’ 的所有城市的清单)。

Because {% regroup %} produces namedtuple() objects, you can also write the previous example as:

{% regroup cities by country as country_list %}

<ul>
{% for country, local_cities in country_list %}
    <li>{{ country }}
    <ul>
        {% for city in local_cities %}
          <li>{{ city.name }}: {{ city.population }}</li>
        {% endfor %}
    </ul>
    </li>
{% endfor %}
</ul>

请注意,{% regroup %} 并没有对其输入进行排序!我们的例子依赖于这样一个事实: cities 列表首先是按 country 排序的。如果 cities 列表没有按 country 排序,重新分组就会天真地显示一个国家的多个组。例如,如果 cities 列表设置成这样(注意,国家没有被归为一组)。

cities = [
    {"name": "Mumbai", "population": "19,000,000", "country": "India"},
    {"name": "New York", "population": "20,000,000", "country": "USA"},
    {"name": "Calcutta", "population": "15,000,000", "country": "India"},
    {"name": "Chicago", "population": "7,000,000", "country": "USA"},
    {"name": "Tokyo", "population": "33,000,000", "country": "Japan"},
]

有了这个 cities 的输入,上面的 {% regroup %} 模板代码就会有如下输出。

  • India
    • Mumbai: 19,000,000
  • USA
    • New York: 20,000,000
  • India
    • Calcutta: 15,000,000
  • USA
    • Chicago: 7,000,000
  • Japan
    • Tokyo: 33,000,000

解决这个问题最简单的方法是在你的视图代码中确保数据是按照你想显示的方式来排序的。

Another solution is to sort the data in the template using the dictsort filter, if your data is in a list of dictionaries:

{% regroup cities|dictsort:"country" by country as country_list %}

对其他属性进行分组

Any valid template lookup is a legal grouping attribute for the regroup tag, including methods, attributes, dictionary keys and list items. For example, if the “country” field is a foreign key to a class with an attribute “description,” you could use:

{% regroup cities by country.description as country_list %}

Or, if country is a field with choices, it will have a get_FOO_display() method available as an attribute, allowing you to group on the display string rather than the choices key:

{% regroup cities by get_country_display as country_list %}

{{ country.grouper }} 现在将显示 choices 集的值域,而不是键。

resetcycle

重置之前的 cycle ,使其在下一次遇到时从第一项开始重新启动。如果没有参数,{% resetcycle %} 将重置模板中定义的最后一个 {% cycle %}。

使用实例:

{% for coach in coach_list %}
    <h1>{{ coach.name }}</h1>
    {% for athlete in coach.athlete_set.all %}
        <p class="{% cycle 'odd' 'even' %}">{{ athlete.name }}</p>
    {% endfor %}
    {% resetcycle %}
{% endfor %}

This example would return this HTML:

<h1>Gareth</h1>
<p class="odd">Harry</p>
<p class="even">John</p>
<p class="odd">Nick</p>

<h1>John</h1>
<p class="odd">Andrea</p>
<p class="even">Melissa</p>

请注意第一个代码块以 class="odd" 结束,而新的代码块以 class="odd" 开始。如果没有 {% resetcycle %} 标签,第二块将以 class="even" 开始。

You can also reset named cycle tags:

{% for item in list %}
    <p class="{% cycle 'odd' 'even' as stripe %} {% cycle 'major' 'minor' 'minor' 'minor' 'minor' as tick %}">
        {{ item.data }}
    </p>
    {% ifchanged item.category %}
        <h1>{{ item.category }}</h1>
        {% if not forloop.first %}{% resetcycle tick %}{% endif %}
    {% endifchanged %}
{% endfor %}

在这个例子中,我们既有奇数/偶数行的交替,也有每第五行的 “主要” 行。只有当类别发生变化时,才会重置五行循环。

spaceless

删除 HTML 标签之间的空白。这包括制表符和换行符。

使用实例:

{% spaceless %}
    <p>
        <a href="foo/">Foo</a>
    </p>
{% endspaceless %}

This example would return this HTML:

<p><a href="foo/">Foo</a></p>

Only space between tags is removed — not space between tags and text. In this example, the space around Hello won’t be stripped:

{% spaceless %}
    <strong>
        Hello
    </strong>
{% endspaceless %}

templatetag

输出用于组成模板标签的语法字符之一。

The template system has no concept of “escaping” individual characters. However, you can use the {% templatetag %} tag to display one of the template tag character combinations.

这个参数告诉我们要输出哪个模板位:

参数 输出
openblock {%
closeblock %}
openvariable {{
closevariable }}
openbrace {
closebrace }
opencomment {#
closecomment #}

Sample usage:

The {% templatetag openblock %} characters open a block.

另请参阅 verbatim 标签以了解包含这些字符的另一种方式。

url

返回与给定视图和可选参数相匹配的绝对路径引用(不含域名的 URL)。路径中的任何特殊字符将使用 iri_to_uri() 进行编码。

This is a way to output links without violating the DRY principle by having to hard-code URLs in your templates:

{% url 'some-url-name' v1 v2 %}

The first argument is a URL pattern name. It can be a quoted literal or any other context variable. Additional arguments are optional and should be space-separated values that will be used as arguments in the URL. The example above shows passing positional arguments. Alternatively you may use keyword syntax:

{% url 'some-url-name' arg1=v1 arg2=v2 %}

不要在一次调用中同时混合使用位置和关键字语法。URLconf 所要求的所有参数都应该存在。

例如,假设你有一个视图,app_views.client,它的 URLconf 需要一个客户端 ID(这里,client() 是视图文件 app_views.py 中的一个方法)。URLconf 行可能是这样的:

path("client/<int:id>/", app_views.client, name="app-views-client")

如果这个应用的 URLconf 被包含在项目的 URLconf 中,路径如下:

path("clients/", include("project_name.app_name.urls"))

…then, in a template, you can create a link to this view like this:

{% url 'app-views-client' client.id %}

模板标签将输出字符串 /clients/client/123/。

请注意,如果你要反查的 URL 不存在,你会得到一个 NoReverseMatch 的异常引发,这将导致你的网站显示一个错误页面。

If you’d like to retrieve a URL without displaying it, you can use a slightly different call:

{% url 'some-url-name' arg arg2 as the_url %}

<a href="{{ the_url }}">I'm linking to {{ the_url }}</a>

as var 语法创建的变量范围是 {% block %},其中出现 {% url %} 标签。

This {% url ... as var %} syntax will not cause an error if the view is missing. In practice you’ll use this to link to views that are optional:

{% url 'some-url-name' as the_url %}
{% if the_url %}
  <a href="{{ the_url }}">Link to optional stuff</a>
{% endif %}

If you’d like to retrieve a namespaced URL, specify the fully qualified name:

{% url 'myapp:view-name' %}

这将遵循正常的 命名空间 URL 解析策略,包括使用上下文提供的关于当前应用程序的任何提示。

警告

不要忘记在 URL 模式的 name 周围加上引号,否则其值将被解释为一个上下文变量!

verbatim

停止模板引擎渲染此块标签的内容。

A common use is to allow a JavaScript template layer that collides with Django’s syntax. For example:

{% verbatim %}
    {{if dying}}Still alive.{{/if}}
{% endverbatim %}

You can also designate a specific closing tag, allowing the use of {% endverbatim %} as part of the unrendered contents:

{% verbatim myblock %}
    Avoid template rendering via the {% verbatim %}{% endverbatim %} block.
{% endverbatim myblock %}

widthratio

对于创建条形图等,该标签计算给定值与最大值的比率,然后将该比率应用于一个常数。

例如:

<img src="bar.png" alt="Bar"
     height="10" width="{% widthratio this_value max_value max_width %}">

如果 this_value 是175,max_value 是 200,max_width 是 100,则上例中的图像宽度为 88 像素(因为 175 / 200 = 0.875;0.875 * 100 = 87.5,四舍五入为 88)。

In some cases you might want to capture the result of widthratio in a variable. It can be useful, for instance, in a blocktranslate like this:

{% widthratio this_value max_value max_width as width %}
{% blocktranslate %}The width is: {{ width }}{% endblocktranslate %}

with

将一个复杂的变量缓存在一个简单的名称下。当多次访问一个 “昂贵的” 方法(例如,访问数据库的方法)时,这很有用。

例如:

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

被填充的变量(在上面的例子中,total)只有在 {% with %} 和 {% endwith %} 标签之间才能使用。

You can assign more than one context variable:

{% with alpha=1 beta=2 %}
    ...
{% endwith %}

备注

仍然支持以前比较啰嗦的格式: {% with business.employees.count as total %}。

内置过滤器参考

add

将参数添加到值中。

例如:

{{ value|add:"2" }}

如果 value 是 4,那么输出将是 6。

这个过滤器将首先尝试将两个值强制转为整数。如果失败了,它将尝试将两个值加在一起。这对某些数据类型(字符串、列表等)有效,而对其他类型则失败。如果失败,结果将是一个空字符串。

For example, if we have:

{{ first|add:second }}

同时 first 是 [1, 2, 3] 并且 second 是 [4, 5, 6],则输出为 [1, 2, 3, 4, 5, 6]。

警告

可以强制转为整数的字符串将被 相加 ,而不是像上面上一个例子那样被连在一起。

addslashes

在引号前添加斜杠。对 CSV 中的字符串进行转义很有用,例如。

例如:

{{ value|addslashes }}

如果 value 是 "I'm using Django",那么输出将是 "I\'m using Django"。

capfirst

将值的第一个字符大写。如果第一个字符不是字母,这个过滤器就没有效果。

例如:

{{ value|capfirst }}

如果 value 是 "django",则输出为 "Django"。

center

在给定宽度的字段中使数值居中。

例如:

"{{ value|center:"15" }}"

如果 value 是 "Django",输出将是 " Django "。

cut

从给定的字符串中删除参数的所有值。

例如:

{{ value|cut:" " }}

如果 value 是 "String with spaces",输出将是 "Stringwithspaces"。

date

根据给定的格式设置日期。

使用与 PHP 的 date() 函数类似的格式,但有一些差异。

备注

这些格式字符在模板之外的 Django 中没有使用。它们被设计成与 PHP 兼容,以方便设计师过渡。

可用的格式字符串:

格式字符 描述 输出示例
日
d 某月的某日,2 位带前导零的数字。 ‘01’ 到 ‘31’
j 某月的某日,前面没有零。 ‘1’ 到 ‘31’
D 某周的某日,3 个字母的文本。 ‘Fri’
l 某周的某日,长文本。 ‘Friday’
S 某月英文序号后缀的某日,2 个字符。 ‘st’、‘nd’、‘rd’ 或 ‘th’
w 某周的某日,不含前导零的数字。 ‘0’ (星期天)到 ‘6’ (星期六)
z 某年的某日 1 到 366
周
W 年的 ISO-8601 周数,周从星期一开始。 1,53
月
m 月份,2 位数,前面加 0。 ‘01’ 到 ‘12’
n 没有前导零的月份。 ‘1’ 到 ‘12’
M 月,3 个字母的文本。 ‘Jan’
b 月,小写的 3 个字母的文本。 ‘jan’
E 月,特定地域的替代表示方法,通常用于长日期表示。 ‘listopada’ (波兰语,与 ‘Listopad’ 相对)
F 月,长文本。 ‘January’
N 美联社风格的月份缩写。专属扩展。 ‘Jan.’、‘Feb.’、‘March’、‘May’
t 特定月份的天数。 28 到 31
年
y 年,2 位带前导零的数字。 ‘00’ 到 ‘99’
Y 年,4 位带前导零的数字。 ‘0001’, …, ‘1999’, …, ‘9999’
L 是否为闰年的布尔值。 True 或 False
o ISO-8601 周数年,对应于使用闰周的 ISO-8601 周数(W)。更常见的年份格式见 Y。 ‘1999’
时间
g 小时,12 小时格式,无前导零。 ‘1’ 到 ‘12’
G 小时,24 小时格式,无前导零。 ‘0’ 到 ‘23’
h 小时,12 小时格式。 ‘01’ 到 ‘12’
H 小时,24 小时格式。 ‘00’ 到 ‘23’
i 分钟。 ‘00’ 到 ‘59’
s 秒,2 位带前导零的数字。 ‘00’ 到 ‘59’
u 微秒。 000000 到 999999
a ‘a.m.’ 或 ‘p.m.’ (请注意,这与 PHP 的输出略有不同,因为这包括了与美联社风格一致的句号)。 ‘a.m.’
A ‘AM’ 或 ‘PM’。 ‘AM’
f 时间,以 12 小时格式的小时和分钟为单位,如果是零,就把分钟去掉。专属扩展。 ‘1’,‘1:30’
P 时间,以 12 小时格式的小时、分钟和 ‘a.m.’/’p.m.’ 为单位,如果分钟为零,则不写,如果有,则写上特殊大小写的字符串 ‘midnight’ 和 ‘noon’。专属扩展。 ‘1 a.m.’、‘1:30 p.m.’、‘midnight’、‘noon’、‘12:30 p.m.’
时区
e 时区名称。可以是任何格式,也可以返回一个空字符串,取决于日期时间。 ‘’、‘GMT’、‘-500’、‘US/Eastern’ 等。
I 夏令时,无论是否生效。 ‘1’ 或 ‘0’
O 与格林威治时间的时差。 ‘+0200’
T 本机的时区。 ‘EST’、‘MDT’
Z 时区偏移以秒为单位。UTC 以西的时区偏移总是负数,UTC 以东的时区偏移总是正数。 -43200 到 43200
日期/时间
c ISO 8601 格式。 (注意:与“Z”、“O”或“r”等其他格式化程序不同,如果值是原始日期时间,“c”格式化程序将不会添加时区偏移量(参见 datetime.tzinfo)。 2008-01-02T10:30:00.000123+02:00 或 2008-01-02T10:30:00.000123 如果日期时间是本地的
r RFC 5322 格式的日期。 ‘Thu, 21 Dec 2000 16:01:07 +0200’
U 自 Unix 纪元(1970 年 1 月 1 日 00:00:00 UTC)以来的秒数。

例如:

{{ value|date:"D d M Y" }}

如果 value 是一个 datetime 对象(例如,datetime.datetime.datetime.now() 的结果),输出将是字符串 'Wed 09 Jan 2008'。

传递的格式可以是预定义的 DATE_FORMAT、DATETIME_FORMAT、SHORT_DATE_FORMAT 或 SHORT_DATETIME_FORMAT, 或者是使用上表中显示的格式指定器的自定义格式。请注意,预定义的格式可能会根据当前的 locale 而有所不同。

Assuming that LANGUAGE_CODE is, for example, "es", then for:

{{ value|date:"SHORT_DATE_FORMAT" }}

输出将是字符串 "09/01/2008" (Django 自带的 "SHORT_DATE_FORMAT" 格式指定符是 "d/m/Y")。

When used without a format string, the DATE_FORMAT format specifier is used. Assuming the same settings as the previous example:

{{ value|date }}

输出 9 de Enero de 2008 (DATE_FORMAT' 格式指定符为 r'j\d\e F\d\e Y')。“d” 和 “e” 都是反斜杠,因为否则每一个都是一个格式字符串,分别显示日期和时区名称。

You can combine date with the time filter to render a full representation of a datetime value. E.g.:

{{ value|date:"D d M Y" }} {{ value|time:"H:i" }}

default

如果值为 False,则使用给定的默认值。否则,使用该值。

例如:

{{ value|default:"nothing" }}

如果 value 是 "" (空字符串),输出将是 nothing。

default_if_none

如果(也只有当)值是 None,使用给定的默认值。否则,使用该值。

请注意,如果给定一个空字符串,将 不会 使用默认值。如果你想使用空字符串,请使用 default 过滤器。

例如:

{{ value|default_if_none:"nothing" }}

如果 value 是 None,则输出为 nothing。

dictsort

获取一个字典列表,并按照参数中给出的键排序返回该列表。

例如:

{{ value|dictsort:"name" }}

如果 value 是:

[
    {"name": "zed", "age": 19},
    {"name": "amy", "age": 22},
    {"name": "joe", "age": 31},
]

那么输出将是:

[
    {"name": "amy", "age": 22},
    {"name": "joe", "age": 31},
    {"name": "zed", "age": 19},
]

You can also do more complicated things like:

{% for book in books|dictsort:"author.age" %}
    * {{ book.title }} ({{ book.author.name }})
{% endfor %}

如果 books 是:

[
    {"title": "1984", "author": {"name": "George", "age": 45}},
    {"title": "Timequake", "author": {"name": "Kurt", "age": 75}},
    {"title": "Alice", "author": {"name": "Lewis", "age": 33}},
]

那么输出将是:

* Alice (Lewis)
* 1984 (George)
* Timequake (Kurt)

dictsort can also order a list of lists (or any other object implementing __getitem__()) by elements at specified index. For example:

{{ value|dictsort:0 }}

如果 value 是:

[
    ("a", "42"),
    ("c", "string"),
    ("b", "foo"),
]

那么输出将是:

[
    ("a", "42"),
    ("b", "foo"),
    ("c", "string"),
]

You must pass the index as an integer rather than a string. The following produce empty output:

{{ values|dictsort:"0" }}

Ordering by elements at specified index is not supported on dictionaries.

Changed in Django 2.2.26:

In older versions, ordering elements at specified index was supported on dictionaries.

dictsortreversed

取一个字典列表,并按参数中给出的键反向排序返回该列表。这与上面的过滤器的工作原理完全相同,但返回的值将是倒序的。

divisibleby

如果数值被参数整除,则返回 True。

例如:

{{ value|divisibleby:"3" }}

如果 value 是 21,则输出为 True。

escape

转义字符串的 HTML。具体来说,它可以进行这些替换。

  • < 被替换为 &lt;
  • > 被替换为 &gt;
  • ' (单引号)被替换为 &#x27;
  • " (双引号)被替换为 &quot;
  • & 被替换为 &amp;

将 escape 应用到一个通常会对结果进行自动转义的变量上,结果只会进行一轮转义。所以即使在自动转义环境中使用这个函数也是安全的。如果你想进行多次转义,请使用 force_escape 过滤器。

For example, you can apply escape to fields when autoescape is off:

{% autoescape off %}
    {{ title|escape }}
{% endautoescape %}

Chaining escape with other filters

As mentioned in the autoescape section, when filters including escape are chained together, it can result in unexpected outcomes if preceding filters mark a potentially unsafe string as safe due to the lack of escaping caused by autoescape being off.

In such cases, chaining escape would not reescape strings that have already been marked as safe.

This is especially important when using filters that operate on sequences, for example join. If you need to escape each element in a sequence, use the dedicated escapeseq filter.

escapejs

Escapes characters for use as a whole JavaScript string literal, within single or double quotes, as below. This filter does not make the string safe for use in “JavaScript template literals” (the JavaScript backtick syntax). Any other uses not listed above are not supported. It is generally recommended that data should be passed using HTML data- attributes, or the json_script filter, rather than in embedded JavaScript.

例如:

<script>
let myValue = '{{ value|escapejs }}'

escapeseq

New in Django 5.0.

Applies the escape filter to each element of a sequence. Useful in conjunction with other filters that operate on sequences, such as join. For example:

{% autoescape off %}
    {{ my_list|escapeseq|join:", " }}
{% endautoescape %}

filesizeformat

以 “人类可读” 的文件大小为格式(如 '13 KB'、'4.1 MB'、'102 bytes' 等)。

例如:

{{ value|filesizeformat }}

如果 value 是 123456789,则输出为 117.7 MB。

文件大小和 SI 单位

严格来说,filesizeformat 并不符合国际单位制,国际单位制建议在字节大小以 1024 的幂计算时使用 KiB、MiB、GiB 等单位(这里就是这种情况)。相反,Django 使用了传统的单位名称(KB、MB、GB 等),对应的是比较常用的名称。

first

返回列表中的第一个项目。

例如:

{{ value|first }}

如果 value 是列表 ['a', 'b', 'c'],则输出为 'a'。

floatformat

当不使用参数时,将浮点数四舍五入到小数点后一位——但只在有小数部分要显示的情况下。例如:

value 模板 输出
34.23234 {{ value|floatformat }} 34.2
34.00000 {{ value|floatformat }} 34
34.26000 {{ value|floatformat }} 34.3

如果与数字整数参数一起使用,floatform 将一个数字四舍五入到小数点后几位。例如:

value 模板 输出
34.23234 {{ value|floatformat:3 }} 34.232
34.00000 {{ value|floatformat:3 }} 34.000
34.26000 {{ value|floatformat:3 }} 34.260

特别有用的是传递 0(零)作为参数,它将把浮点数舍入到最接近的整数。

value 模板 输出
34.23234 {{ value|floatformat:”0” }} 34
34.00000 {{ value|floatformat:”0” }} 34
39.56000 {{ value|floatformat:”0” }} 40

如果传递给 floatform 的参数是负数,它将把一个数字四舍五入到小数点后的位数——但只在有小数部分要显示的情况下。例如:

value 模板 输出
34.23234 {{ value|floatformat:”-3” }} 34.232
34.00000 {{ value|floatformat:”-3” }} 34
34.26000 {{ value|floatformat:”-3” }} 34.260

If the argument passed to floatformat has the g suffix, it will force grouping by the THOUSAND_SEPARATOR for the active locale. For example, when the active locale is en (English):

value 模板 输出
34232.34 {{ value|floatformat:”2g” }} 34,232.34
34232.06 {{ value|floatformat:”g” }} 34,232.1
34232.00 {{ value|floatformat:”-3g” }} 34,232

Output is always localized (independently of the {% localize off %} tag) unless the argument passed to floatformat has the u suffix, which will force disabling localization. For example, when the active locale is pl (Polish):

value 模板 输出
34.23234 {{ value|floatformat:”3” }} 34,232
34.23234 {{ value|floatformat:”3u” }} 34.232

在没有参数的情况下使用 floatformat 相当于在参数为 -1 的情况下使用 floatformat。

force_escape

对字符串进行 HTML 转义处理(详情请参见 escape 过滤器)。这个过滤器会 立即 应用,并返回一个新的转义字符串。在极少数情况下,当你需要多次转义或想对转义结果应用其他过滤器时,这很有用。通常情况下,你要使用 escape 过滤器。

For example, if you want to catch the <p> HTML elements created by the linebreaks filter:

{% autoescape off %}
    {{ body|linebreaks|force_escape }}
{% endautoescape %}

get_digit

给定一个整数,返回要求的数字,其中 1 是最右边的数字,2 是最右边的数字,等等。对于无效的输入(如果输入或参数不是整数,或者参数小于 1),返回原始值。否则,输出总是一个整数。

例如:

{{ value|get_digit:"2" }}

如果 value 是 123456789,则输出为 8。

iriencode

将 IRI(国际化资源标识符)转换为适合包含在 URL 中的字符串。如果你想在 URL 中使用包含非 ASCII 字符的字符串,这一点是必要的。

在已经通过 urlencode 过滤器的字符串上使用这个过滤器是安全的。

例如:

{{ value|iriencode }}

如果 value 是 "?test=1&me=2",则输出为 "?test=1&amp;me=2"。

join

用字符串连接一个列表,就像 Python 的 str.join(list) 一样。

例如:

{{ value|join:" // " }}

如果 value 是列表 ['a', 'b', 'c'],输出将是字符串 "a // b // c"。

json_script

安全地将 Python 对象输出为 JSON,用 <script> 标签包装,准备好与 JavaScript 一起使用。

Argument: The optional HTML “id” of the <script> tag.

例如:

{{ value|json_script:"hello-data" }}

如果 value 是字典 {'hello':'world'},则输出为:

<script id="hello-data" type="application/json">{"hello": "world"}</script>

由此产生的数据可以用 JavaScript 来访问,比如这样:

const value = JSON.parse(document.getElementById('hello-data').textContent);

XSS 攻击可以通过转义字符 “<”、“>” 和 “&” 来缓解。例如,如果 value 是 {'hello': 'world</script>&amp;'},则输出为:

<script id="hello-data" type="application/json">{"hello": "world\\u003C/script\\u003E\\u0026amp;"}</script>

这与严格的内容安全策略兼容,禁止在页面中执行脚本。它还保持了被动数据和可执行代码之间的明确分离。

last

返回列表中的最后一项。

例如:

{{ value|last }}

如果 value 是列表 ['a', 'b', 'c', 'd'],输出将是字符串 "d"。

length

返回值的长度。这对字符串和列表都有效。

例如:

{{ value|length }}

如果 value 是 ['a', 'b', 'c', 'd'] 或 "abcd",输出将是 4。

过滤器对未定义的变量返回 0。

length_is

4.2 版后已移除.

如果值的长度是参数,则返回 True,否则返回 False。

例如:

{{ value|length_is:"4" }}

如果 value 是 ['a', 'b', 'c', 'd'] 或 "abcd",输出将是 True。

linebreaks

用适当的 HTML 替换纯文本中的换行符;一个新行成为 HTML 换行符(<br>),一个新行后的空行成为段落换行符(</p>)。

例如:

{{ value|linebreaks }}

如果 value 是 Joel\nis a slug,则输出为 <p>Joel<br>is a slug</p>。

linebreaksbr

将一段纯文本中的所有换行符转换为 HTML 换行符(<br>)。

例如:

{{ value|linebreaksbr }}

如果 value 是 Joel/nis a slug,则输出为 Joel<br>is a slug。

linenumbers

显示带有行号的文本。

例如:

{{ value|linenumbers }}

如果 value 是:

one
two
three

the output will be:

1. one
2. two
3. three

ljust

左对齐给定宽度的字段中的值。

参数: 字段大小

例如:

"{{ value|ljust:"10" }}"

如果 value 是 Django,则输出为 "Django "。

lower

将一个字符串转换为全小写。

例如:

{{ value|lower }}

如果 value 是 Totally LOVING this Album!,则输出为 totally loving this album!。

make_list

返回变成列表的值。对于字符串,它是一个字符列表。对于整数来说,在创建列表之前,参数会被转换为一个字符串。

例如:

{{ value|make_list }}

如果 value 是字符串 "Joel",输出将是列表 ['J', 'o', 'e', 'l']。如果 value 是 123,输出将是列表 ['1','2','3']。

phone2numeric

将一个电话号码(可能包含字母)转换为其数字等价物。

输入的不一定是有效的电话号码。这将很乐意转换任何字符串。

例如:

{{ value|phone2numeric }}

如果 value 是 800-COLLECT,则输出为 800-2655328。

pluralize

如果值不是 1、'1' 或长度为 1 的对象,则返回复数后缀。 默认情况下,后缀为 's'。

Example:

You have {{ num_messages }} message{{ num_messages|pluralize }}.

如果 num_messages 是 1,输出将是 You have 1 message. 如果 num_messages 是 2,输出将是 You have 2 messages.。

对于需要后缀而不是 's' 的词,你可以提供一个备用后缀作为过滤器的参数。

Example:

You have {{ num_walruses }} walrus{{ num_walruses|pluralize:"es" }}.

对于不使用简单后缀进行复数的单词,你可以同时指定单数和复数后缀,并用逗号分隔。

Example:

You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.

备注

使用 blocktranslate 来实现翻译字符串的复数化。

pprint

pprint.pprint() 的一个包装器 —— 真的是用来调试的。

random

从给定列表中随机返回一个项目。

例如:

{{ value|random }}

如果 value 是列表 ['a', 'b', 'c', 'd'],输出可能是 "b"。

rjust

右对齐给定宽度的字段中的值。

参数: 字段大小

例如:

"{{ value|rjust:"10" }}"

如果 value 是 Django,输出将是 " Django"。

(本文超出站点单文档体积上限,已按小节截断)