Django 1.8.2 文档

内置标签与过滤器

本文档介绍了Django的内置模板标签和过滤器。 我们推荐尽可能使用 自动文档,同时也可以自行编辑任何已安装的自定义标签或过滤器的文档。

内置标记引用

autoescape

控制自动转义是否可用.这种标签带有任何 onoff 作为参数的话,他将决定转义块内效果。该标签会以一个endautoescape作为结束标签.

当自动转义生效时,所有变量内容会被转义成HTML输出(在所有过滤器生效后)这等同与手动将escape筛选器应用于每个变量。

唯一的例外是,当变量已经被标记为“safe”,或者是因为通过渲染变量的代码,又或者是因为它已经应用了 safeescape过滤器。

例如:

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

block

block标签可以被子模板覆盖.查看 模板继承 可以获得更多信息.

comment(注释)

{% comment %}{% endcomment %},之间的内容会被忽略,作为注释。在第一个标签可以插入一个可选的记录。 比如,当要注释掉一些代码时,可以用此来记录代码被注释掉的原因。

简单实例:

<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

这个标签用于跨站请求伪造保护, 具体可以参考Cross Site Request Forgeries中的描述。

cycle

每当这个标签被访问,则传出一个它的可迭代参数的元素。第一次访问返回第一个元素,第二次访问返回第二个参数,以此类推.一旦所有的变量都被访问过了,就会回到最开始的地方,重复下去

这个标签在循环中特别有用:

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

第一次迭代产生的HTML引用了 row1类,第二次则是row2类,第三次 又是row1 类,如此类推。

你也可以使用变量,例如,如果你有两个模版变量, rowvalue1rowvalue2, 你可以让他们的值像这样替换:

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

被包含在cycle中的变量将会被转义。你可以禁止自动转义:

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

你能混合使用变量和字符串:

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

在某些情况下,您可能需要连续引用一个当前循环的值,而不前进到下一个循环值。要达到这个目的,只需使用“as”来给{% cycle %}一个别名,就像这样:

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

从那时起(设置别名后),你可以通过将别名作为一个模板变量进行引用,从而随意在模板中插入当前循环的值。如果要将循环值移动到独立于原始cycle标记的下一个值,可以使用另一个cycle标记并指定变量的名称。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 标签中,通过空格分割,你可以使用任意数量的值。被包含在单引号 (')或者双引号 (") 中的值被认为是可迭代字符串,相反,没有被引号包围的值被当作模版变量。

默认情况下,当你在cycle标签中使用as 关键字时,关于{% cycle %}的使用,会启动cycle并且直接产生第一个值。如果你想要在嵌套循环中或者included模版中使用这个值,那么将会遇到困难。如果你只是想要声明cycle,但是不产生第一个值,你可以添加一个silent关键字来作为cycle标签的最后一个关键字。例如:

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

这将输出<tr>元素的列表,其中classrow1row2之间交替。子模板将在其上下文中访问rowcolors,并且该值将匹配包围它的<tr>的类。如果省略silent关键字,则row1row2将作为正常文本发出,<tr>

当在循环定义上使用silent关键字时,静默将自动应用于该特定周期标记的所有后续使用。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 %}

为了向后兼容,{% cycle %}标记支持来自以前Django版本的劣质旧语法。你不应该在任何新项目中使用它,但是为了仍在使用它的人,这里是它的样子:

{% cycle row1,row2,row3 %}

在这里,每个值都是字符串,并且无法置顶变量名或者直接的逗号或空格。我们提到你不应该在任何新项目中使用这种语法?

debug

输出整个调试信息,包括当前上下文和导入的模块。

extends

表示当前模板继承自一个父模板

这个标签可以有两种用法:

  • {% extends "base.html" %} (要有引号).继承名为"base.html"的父模板
  • {% extends variable %} 使用variable的值. 如果变量被计算成一个字符串,Django将会把它看成是父模版的名字。如果变量被计算到一个Template对象,Django将会使用那个对象作为一个父模版。

阅读 Template inheritance 获取更多信息

filter

通过一个或多个过滤器对内容过滤。 作为灵活可变的语法,多个过滤器被管道符号相连接,且过滤器可以有参数。

注意块中所有的内容都应该包括在filterendfilter 标签中。

简单用例:

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

注意

The escape and safe filters are not acceptable arguments. 取而代之的是, 使用autoescape 标签来管理模板代码块的自动转义.

firstof

输出第一个不为False参数。如果传入的所有变量都为False,就什么也不输出。

简单用例:

{% firstof var1 var2 var3 %}

它等价于:

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

当然你也可以用一个默认字符串作为输出以防传入的所有变量都是False:

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

标签auto-escapes是开启的, 你可以这样关闭auto-escaping:

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

如果只想要部分变量被规避,可以这样使用:

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

for

循环组中的每一个项目,并让这些项目在上下文可用。 举个例子,展示athlete_list中的每个成员:

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

可以利用{% for obj in list reversed %}反向完成循环。

如果你需要循环一个包含列表的列表,可以通过拆分每一个二级列表为一个独立变量来达到目的。 举个例子,如果你的内容包括一个叫做points的(x,y) 列表,你可以像以下例子一样输出points列表:

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

如果你想访问一个字典中的项目,这个方法同样有用。举个例子:如果你的内容包含一个叫做data的字典,下面的方式可以输出这个字典的键和值:

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

The current iteration of the loop (1-indexed)

Variable Description
forloop.counter The current iteration of the loop (1-indexed)
forloop.counter0 The current iteration of the loop (0-indexed)
forloop.revcounter The number of iterations from the end of the loop (1-indexed)
forloop.revcounter0 The number of iterations from the end of the loop (0-indexed)
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 For nested loops, this is the loop surrounding the current one

for ... empty

for 标签带有一个可选的{% empty %} 从句,以便在给出的组是空的或者没有被找到时,可以有所操作。

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

它和下面的例子作用相等,但是更简洁、更清晰甚至可能运行起来更快:

<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

{% if %}会对一个变量求值,如果它的值是“True”(存在、不为空、且不是boolean类型的false值),这个内容块会输出:

{% 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 }}过滤器展示出athletes的数量。

正如你所见,if标签之后可以带有一个或者多个{% elif %} 从句,也可以带有一个{% else %}从句以便在之前的所有条件不成立的情况下完成执行。这些从句都是可选的。

Boolean operators

if 标签可能使用 andornot 来测试一些变量或对给定变量取反:

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

同一标签中andor 分句的使用是允许的,此时andor有更高的优先级,例如:

{% if athlete_list and coach_list or cheerleader_list %}

将会像这样解释:

if (athlete_list and coach_list) or cheerleader_list

if标签中使用真实的圆括号是无效语法. 如果你需要他们来表明优先级,你需要使用嵌套的if 标签.

if 标签还可能使用 ==, !=, <, >, <=, >=in ,他们作用如下:

== operator

相等。例:

{% if somevar == "x" %}
  This appears if variable somevar equals the string "x"
{% endif %}

!= operator

不相等。例:

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

< operator

小于。例:

{% if somevar < 100 %}
  This appears if variable somevar is less than 100.
{% endif %}

> operator

大于。例:

{% if somevar > 0 %}
  This appears if variable somevar is greater than 0.
{% endif %}

<= operator

小于或等于。例:

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

>= operator

大于或等于。例:

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

in operator

包含在内。许多Python容器支持此运算符,以测试给定值是否在容器中。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运算符的否定操作。

比较运算符不能像Python或数学符号中那样“链接”。例如,不能使用:

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

你应该使用:

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

过滤器

您也可以在if表达式中使用过滤器。举个例子:

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

复合表达式

所有上述操作符可以组合以形成复杂表达式。对于这样的表达式,重要的是要知道在表达式求值时如何对运算符进行分组 - 即优先级规则。操作符的优先级从低至高如下:

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

(这完全依据Python)。所以,例如,下面的复杂if标签:

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

...将被解释为:

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

如果你想要不同的优先级,那么你需要使用嵌套的if 标签。Sometimes that is better for clarity anyway, for the sake of those who do not know the precedence rules.

ifchanged

检查一个值是否在上一次的迭代中改变。

{% ifchanged %} 块标签用在循环里。它可能有两个用处:

  1. 检查它已经渲染过的内容中的先前状态。并且只会显示发生改变的内容。例如, 以下的代码是输出days的列表项,不过它只会输出被修改过月份的项:

    <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 %}
    
  2. 如果标签内被给予多个值时,则会比较每一个值是否与上一次不同。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 %}

ifequal

如果给定的两个参数是相等的,则显示被标签包含的内容.

举个例子:

{% ifequal user.pk comment.user_id %}
    ...
{% endifequal %}

if 标签里面, 也可以包含 {% else %} 标签选项.

参数可以是一个硬编码的字符串,所以也可以这样:

{% ifequal user.username "adrian" %}
    ...
{% endifequal %}

ifequal标记的替代方法是使用if标记和==运算符。

ifnotequal

就像ifequal,不过它测试两个参数不相等。

ifnotequal标记的替代方法是使用if标记和!=运算符。

include

加载模板并以标签内的参数渲染。这是一种可以引入别的模板的方法。

模板名可以是变量或者是硬编码的字符串,可以用单引号也可以是双引号.

下面这个示例包括模板“foo/bar.html”的内容:

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

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

{% include template_name %}
Changed in Django 1.7:

变量也可以是任何实现了render() 方法接口的对象,这个对象要可以接收上下文(context)。这就允许你在context中引用一个已经被编译过的Template

被包含的模板在包含它的模板的上下文中渲染。下面这个示例生成输出“Hello, John!”

  • 上下文:变量person设置为“John”,变量greeting设置为“Hello”

  • 模板:

    {% include "name_snippet.html" %}
    
  • name_snippet.html模板:

    {{ greeting }}, {{ person|default:"friend" }}!
    

你可以使用关键字参数将额外的上下文传递到模板:

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

如果要仅使用提供的变量(或根本不使用变量)来渲染上下文,请使用only选项。所包含的模板没有其他变量可用:

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

注意

 include 标签应该被理解为是一种"将子模版渲染并嵌入HTML中"的变种方法,而不是认为是"解析子模版并在被父模版包含的情况下展现其被父模版定义的内容".这意味着在不同的被包含的子模版之间并不共享父模版的状态,每一个子包含都是完全独立的渲染过程.

Block模块在被包含 之前 就已经被执行. 这意味着模版在被包含之前就已经从另一个block扩展并 已经被执行并完成渲染 - 没有block模块会被include引入并执行,即使父模版中的扩展模版.

load

加载自定义模板标签集。

举个例子, 下面这模板将会从package包中载入所有somelibraryotherlibrary 中已经注册的标签和过滤器:

{% load somelibrary package.otherlibrary %}

你还可以使用from参数从库中选择性加载单个过滤器或标记。在下面这个示例中,名为foobar的模板标签/过滤器将从somelibrary加载:

{% load foo bar from somelibrary %}

有关详细信息,请参阅自定义标记和过滤器库

lorem

New in Django 1.8:

该标签之前位于django.contrib.webdesign中。

展示随机的“lorem ipsum”拉丁文本. 这个标签是用来在模版中提供文字样本以供测试用的.

用法:

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

可以使用零个,一个,两个或三个参数使用{% lorem %} 这些参数是:

Argument Description
count A number (or variable) containing the number of paragraphs or words to generate (default is 1).
method Either w for words, p for HTML paragraphs or b for plain-text paragraph blocks (default is b).
random The word random, which if given, does not use the common paragraph (“Lorem ipsum dolor sit amet...”) when generating text.

例子:

  • {% lorem %}将输出常见的“lorem ipsum”段落。
  • {% lorem 3 p %} will output the common “lorem ipsum” paragraph and two random paragraphs each wrapped in HTML <p> tags.
  • {% lorem 2 w random %} will output two random Latin words.

now

显示最近的日期或事件,可以通过给定的字符串格式显示。此类字符串可以包含格式说明符字符,如date过滤器部分中所述。

例:

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

注意!,如果你想要使用“raw”值,你能够反斜杠转义一个格式化字符串。在这个例子中,“o”和“f”都是反斜杠转义,因为如果不这样,会分别显示年和时间:

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

This would display as “It is the 4th of September”.

注意

传递的格式也可以是预定义的DATE_FORMATDATETIME_FORMATSHORT_DATE_FORMATSHORT_DATETIME_FORMAT之一。预定义的格式可能会因当前语言环境和格式本地化的启用而有所不同,例如:

It is {% now "SHORT_DATETIME_FORMAT" %}

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

{% now "Y" as current_year %}
{% blocktrans %}Copyright {{ current_year }}{% endblocktrans %}
New in Django 1.8.

添加了使用“as”语法的能力。

regroup

用相似对象间共有的属性重组列表.

用一个例子来解释这种复杂的标签是最好的方法:假如“places”是一个包含了"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

你可以使用{% regroup %}标签来给每个国家的城市分组。以下模板代码片段将实现这一点:

{% regroup cities by country as country_list %}

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

让我们来看看这个例子。{% regroup %}有三个参数: 你想要重组的列表, 被分组的属性, 还有结果列表的名字. Here, we’re regrouping the cities list by the country attribute and calling the result country_list.

{% regroup %} produces a list (in this case, country_list) of group objects. Each group object has two attributes:

  • grouper – the item that was grouped by (e.g., the string “India” or “Japan”).
  • list – a list of all items in this group (e.g., a list of all cities with country=’India’).

Note that {% regroup %} does not order its input! Our example relies on the fact that the cities list was ordered by country in the first place. If the cities list did not order its members by country, the regrouping would naively display more than one group for a single country. For example, say the cities list was set to this (note that the countries are not grouped together):

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'},
]

With this input for cities, the example {% regroup %} template code above would result in the following output:

  • 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

The easiest solution to this gotcha is to make sure in your view code that the data is ordered according to how you want to display it.

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

Grouping on other properties

一个有效的模版查找是一个regroup标签的合法的分组属性。包括方法,属性,字典健和列表项。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 }} will now display the value fields from the choices set rather than the keys.

spaceless

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

用法示例:

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

这个示例将返回下面的HTML:

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

仅删除 tags 之间的空格 – 而不是标签和文本之间的。在此示例中,Hello周围的空格不会被删除:

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

ssi

从1.8以后不建议使用这标签建议不再使用,将会在Django 2.0以后会被删除。include标签代替。

将给定文件的内容输出到页面。

Like a simple include tag, {% ssi %} includes the contents of another file – which must be specified using an absolute path – in the current page:

{% ssi '/home/html/ljworld.com/includes/right_generic.html' %}

ssi的第一个参数可以是引用的文字或任何其他上下文变量。

If the optional parsed parameter is given, the contents of the included file are evaluated as template code, within the current context:

{% ssi '/home/html/ljworld.com/includes/right_generic.html' parsed %}

Note that if you use {% ssi %}, you’ll need to define 'allowed_include_roots' in the OPTIONS of your template engine, as a security measure.

Note

With the ssi tag and the parsed parameter there is no shared state between files – each include is a completely independent rendering process. This means it’s not possible for example to define blocks or alter the context in the current page using the included file.

See also: {% include %}.

templatetag

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

由于模板系统没有“转义”的概念,为了显示模板标签中使用的一个位,必须使用{% templatetag %}标记。

参数指定要输出哪个模板位:

Argument Outputs
openblock {%
closeblock %}
openvariable {{
closevariable }}
openbrace {
closebrace }
opencomment {#
closecomment #}

样品用量:

{% templatetag openblock %} url 'entry_list' {% templatetag closeblock %}

url

返回一个绝对路径的引用(不包含域名的URL),该引用匹配一个给定的视图函数和一些可选的参数。在解析后返回的结果路径字符串中,每个特殊字符将使用iri_to_uri()编码。

这是一种不违反DRY原则的输出链接的方式,它可以避免在模板中硬编码链接路径。

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

第一个参数是视图函数中包名.模块名.函数名这样的路径package.package.module.function. 它可以是一个被引号引起来的字符串或者其他的上下文变量. 其他参数是可选的并且应该以空格隔开,这些值会在URL中以参数的形式传递. 上面的例子展示了如何传递位置参数.当然你也可以使用关键字参数.

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

不要把位置参数和关键字参数混在一起使用。URLconf所需的所有参数都应该存在。

例如,假设您有一个视图app_views.client,其URLconf接受客户端ID(此处client()是视图文件app_views .py)。URLconf行可能如下所示:

('^client/([0-9]+)/$', 'app_views.client', name='app-views-client')

如果你的应用中的URLconf 已经被包含到项目 URLconf 中,比如下面这样

('^clients/', include('project_name.app_name.urls'))

...那么, 在模板文件中, 你可以很方便的创建一个接指该视图的超链接,示例如下

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

模板标签会输出如下的字符串 /clients/client/123/.

如果您使用命名的网址格式,则可以参考网址标记中的模式名称,而不是使用视图的路径。

请注意,如果您要撤消的网址不存在,您会收到NoReverseMatch异常,这会导致您的网站显示错误网页。

如果您希望在不显示网址的情况下检索网址,则可以使用略有不同的调用:

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

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

The scope of the variable created by the as var syntax is the {% block %} in which the {% url %} tag appears.

{% url ...as var %} 语法将导致错误,如果视图丢失。实际上,您将使用此链接来链接到可选的视图:

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

如果您要检索名称空间网址,请指定完全限定名称:

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

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

Deprecated since version 1.8: The dotted Python path syntax is deprecated and will be removed in Django 2.0:

{% url 'path.to.some_view' v1 v2 %}

Warning

不要忘记在函数路径或模式名称周围加引号,否则值将被解释为上下文变量!

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

For creating bar charts and such, this tag calculates the ratio of a given value to a maximum value, and then applies that ratio to a constant.

For example:

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

If this_value is 175, max_value is 200, and max_width is 100, the image in the above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88).

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

{% widthratio this_value max_value max_width as width %}
{% blocktrans %}The width is: {{ width }}{% endblocktrans %}
Changed in Django 1.7:

The ability to use “as” with this tag like in the example above was added.

with

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

For example:

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

The populated variable (in the example above, total) is only available between the {% with %} and {% endwith %} tags.

你可以分配多个上下文变量:

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

Note

The previous more verbose format is still supported: {% with business.employees.count as total %}

内置过滤器参考

add

把add后的参数加给value

例如:

{{ value|add:"2" }}

如果 value4,则会输出 6.

过滤器首先会强制把两个值转换成Int类型。如果强制转换失败, 它会试图使用各种方式吧两个值相加。它会使用一些数据类型 (字符串, 列表, 等等.) 其他类型则会失败. Day of the month, 2 digits with leading zeros.

例如,我们使用下面的值

{{ first|add:second }}

 first[1, 2, 3]  ,second[4, 5, 6], 将会输出 [1, 2, 3, 4, 5, 6].

警告

如果字符串可以被强制转换成int类型则会 summed,无法被转换,则和上面的第一个例子一样

addslashes

在引号前面加上斜杆。例如,用于在CSV中转义字符串。

例如:

{{ value|addslashes }}

如果value"I'm using Django", 输出将变成 "I\'m using Django".

capfirst

大写变量的第一个字母。如果第一个字符不是字母,该过滤器将不会生效。

例如:

{{ value|capfirst }}

如果 value"django", 输出将变成 "Django".

center

使"value"在给定的宽度范围内居中.

例如:

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

If value is "Django", the output will be "     Django    ".

cut

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

例如:

{{ value|cut:" " }}

如果value“String with spaces”,输出将为"Stringwithspaces"

date

根据给定格式对一个date变量格式化

格式类似于 PHP 的 date() 函数 (http://php.net/date) ,在一些细节上有不同.

注意

这些格式字符不在模板外的Django中使用。它们被设计为与PHP兼容,以便为设计者轻松过渡。

可用的格式字符串:

Format character Description Example output
a 'a.m.' or 'p.m.' (Note that this is slightly different than PHP’s output, because this includes periods to match Associated Press style.) 'a.m.'
A 'AM' or 'PM'. 'AM'
b Month, textual, 3 letters, lowercase. 'jan'
B Not implemented.  
c ISO 8601 format. (Note: unlike others formatters, such as “Z”, “O” or “r”, the “c” formatter will not add timezone offset if value is a naive datetime (see datetime.tzinfo). 2008-01-02T10:30:00.000123+02:00, or 2008-01-02T10:30:00.000123 if the datetime is naive
d Day of the month, 2 digits with leading zeros. '01' to '31'
D Day of the week, textual, 3 letters. 'Fri'
e Timezone name. Could be in any format, or might return an empty string, depending on the datetime. '', 'GMT', '-500', 'US/Eastern', etc.
E Month, locale specific alternative representation usually used for long date representation. 'listopada' (for Polish locale, as opposed to 'Listopad')
f Time, in 12-hour hours and minutes, with minutes left off if they’re zero. Proprietary extension. '1', '1:30'
F Month, textual, long. 'January'
g Hour, 12-hour format without leading zeros. '1' to '12'
G Hour, 24-hour format without leading zeros. '0' to '23'
h Hour, 12-hour format. '01' to '12'
H Hour, 24-hour format. '00' to '23'
i Minutes. '00' to '59'
I Daylight Savings Time, whether it’s in effect or not. '1' or '0'
j Day of the month without leading zeros. '1' to '31'
l Day of the week, textual, long. 'Friday'
L Boolean for whether it’s a leap year. True or False
m Month, 2 digits with leading zeros. '01' to '12'
M Month, textual, 3 letters. 'Jan'
n Month without leading zeros. '1' to '12'
N Month abbreviation in Associated Press style. Proprietary extension. 'Jan.', 'Feb.', 'March', 'May'
o ISO-8601 week-numbering year, corresponding to the ISO-8601 week number (W) '1999'
O Difference to Greenwich time in hours. '+0200'
P Time, in 12-hour hours, minutes and ‘a.m.’/’p.m.’, with minutes left off if they’re zero and the special-case strings ‘midnight’ and ‘noon’ if appropriate. Proprietary extension. '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.'
r RFC 2822 formatted date. 'Thu, 21 Dec 2000 16:01:07 +0200'
s Seconds, 2 digits with leading zeros. '00' to '59'
S English ordinal suffix for day of the month, 2 characters. 'st', 'nd', 'rd' or 'th'
t Number of days in the given month. 28 to 31
T Time zone of this machine. 'EST', 'MDT'
u Microseconds. 000000 to 999999
U Seconds since the Unix Epoch (January 1 1970 00:00:00 UTC).  
w Day of the week, digits without leading zeros. '0' (Sunday) to '6' (Saturday)
W ISO-8601 week number of year, with weeks starting on Monday. 1, 53
y Year, 2 digits. '99'
Y Year, 4 digits. '1999'
z Day of the year. 0 to 365
Z Time zone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 to 43200

For example:

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

If value is a datetime object (e.g., the result of datetime.datetime.now()), the output will be the string 'Wed 09 Jan 2008'.

The format passed can be one of the predefined ones DATE_FORMAT, DATETIME_FORMAT, SHORT_DATE_FORMAT or SHORT_DATETIME_FORMAT, or a custom format that uses the format specifiers shown in the table above. Note that predefined formats may vary depending on the current locale.

Assuming that USE_L10N is True and LANGUAGE_CODE is, for example, "es", then for:

{{ value|date:"SHORT_DATE_FORMAT" }}

the output would be the string "09/01/2008" (the "SHORT_DATE_FORMAT" format specifier for the es locale as shipped with Django is "d/m/Y").

When used without a format string:

{{ value|date }}

...the formatting string defined in the DATE_FORMAT setting will be used, without applying any localization.

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

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

例如:

{{ value|default:"nothing" }}

If value is "" (the empty string), the output will be nothing.

default_if_none

如果(且仅当)value为None,则使用给定的默认值。否则,使用该value。

注意,如果给出一个空字符串,默认值将被使用。如果要回退空字符串,请使用default过滤器。

例如:

{{ value|default_if_none:"nothing" }}

如果valueNone,则输出将为字符串“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},
]

你也可以做更复杂的事情,如:

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

dictsortreversed

获取字典列表,并返回按照参数中给出的键按相反顺序排序的列表。这与上面的过滤器完全相同,但返回的值将是相反的顺序。

divisibleby

如果value可以被给出的参数整除,则返回 True

For example:

{{ value|divisibleby:"3" }}

If value is 21, the output would be True.

escape

转义字符串的HTML。具体来说,它使这些替换:

  • < is converted to &lt;
  • > is converted to &gt;
  • ' (single quote) is converted to &#39;
  • " (double quote) is converted to &quot;
  • & is converted to &amp;

转义仅在字符串输出时应用,因此在连接的过滤器序列中escape的位置无关紧要:它将始终应用,就像它是最后一个过滤器。如果要立即应用转义,请使用force_escape过滤器。

转义应用于通常会对结果应用自动转义的变量只会导致一轮转义完成。因此,即使在自动逃逸环境中使用此功能也是安全的。如果要应用多个转义通过,请使用force_escape过滤器。

例如,您可以在autoescape关闭时将escape应用于字段:

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

escapejs

Escapes characters for use in JavaScript strings. This does not make the string safe for use in HTML, but does protect you from syntax errors when using templates to generate JavaScript/JSON.

For example:

{{ value|escapejs }}

If value is "testing\r\njavascript \'string" <b>escaping</b>", the output will be "testing\\u000D\\u000Ajavascript \\u0027string\\u0022 \\u003Cb\\u003Eescaping\\u003C/b\\u003E".

filesizeformat

格式化数值为“人类可读”的文件大小(例如'13 KB', '4.1 MB', '102 bytes'等)。

例如:

{{ value|filesizeformat }}

如果value 为123456789,输出将是117.7 MB

文件大小和国际系统单位

严格地讲,filesizeformat 没有遵守国际单位系统建议的KiB、MiB、GiB等,它们使用1024 为幂(虽然这里使用的也是)。相反,Django 使用传统的更常用的单位名称(KB、MB、GB等)。

first

返回列表中的第一项。

例如:

{{ value|first }}

如果是列表['a', 'b', 'c'] ,输出将为'a'

floatformat

When used without an argument, rounds a floating-point number to one decimal place – but only if there’s a decimal part to be displayed. For example:

value Template Output
34.23234 {{ value|floatformat }} 34.2
34.00000 {{ value|floatformat }} 34
34.26000 {{ value|floatformat }} 34.3

If used with a numeric integer argument, floatformat rounds a number to that many decimal places. For example:

value Template Output
34.23234 {{ value|floatformat:3 }} 34.232
34.00000 {{ value|floatformat:3 }} 34.000
34.26000 {{ value|floatformat:3 }} 34.260

Particularly useful is passing 0 (zero) as the argument which will round the float to the nearest integer.

value Template Output
34.23234 {{ value|floatformat:"0" }} 34
34.00000 {{ value|floatformat:"0" }} 34
39.56000 {{ value|floatformat:"0" }} 40

If the argument passed to floatformat is negative, it will round a number to that many decimal places – but only if there’s a decimal part to be displayed. For example:

value Template Output
34.23234 {{ value|floatformat:"-3" }} 34.232
34.00000 {{ value|floatformat:"-3" }} 34
34.26000 {{ value|floatformat:"-3" }} 34.260

Using floatformat with no argument is equivalent to using floatformat with an argument of -1.

force_escape

Applies HTML escaping to a string (see the escape filter for details). This filter is applied immediately and returns a new, escaped string. This is useful in the rare cases where you need multiple escaping or want to apply other filters to the escaped results. Normally, you want to use the escape filter.

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

Given a whole number, returns the requested digit, where 1 is the right-most digit, 2 is the second-right-most digit, etc. Returns the original value for invalid input (if input or argument is not an integer, or if argument is less than 1). Otherwise, output is always an integer.

For example:

{{ value|get_digit:"2" }}

If value is 123456789, the output will be 8.

iriencode

Converts an IRI (Internationalized Resource Identifier) to a string that is suitable for including in a URL. This is necessary if you’re trying to use strings containing non-ASCII characters in a URL.

It’s safe to use this filter on a string that has already gone through the urlencode filter.

For example:

{{ value|iriencode }}

If value is "?test=1&me=2", the output will be "?test=1&amp;me=2".

join

Joins a list with a string, like Python’s str.join(list)

For example:

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

If value is the list ['a', 'b', 'c'], the output will be the string "a // b // c".

last

Returns the last item in a list.

For example:

{{ value|last }}

If value is the list ['a', 'b', 'c', 'd'], the output will be the string "d".

length

Returns the length of the value. This works for both strings and lists.

For example:

{{ value|length }}

If value is ['a', 'b', 'c', 'd'] or "abcd", the output will be 4.

Changed in Django 1.8:

The filter returns 0 for an undefined variable. Previously, it returned an empty string.

length_is

Returns True if the value’s length is the argument, or False otherwise.

For example:

{{ value|length_is:"4" }}

If value is ['a', 'b', 'c', 'd'] or "abcd", the output will be True.

linebreaks

Replaces line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (<br />) and a new line followed by a blank line becomes a paragraph break (</p>).

For example:

{{ value|linebreaks }}

If value is Joel is a slug, the output will be <p>Joel<br />is a slug</p>

linebreaksbr

Converts all newlines in a piece of plain text to HTML line breaks (<br />).

For example:

{{ value|linebreaksbr }}

If value is Joel is a slug, the output will be Joel<br />is a slug

linenumbers

Displays text with line numbers.

For example:

{{ value|linenumbers }}

If value is:

one
two
three

the output will be:

1. one
2. two
3. three

ljust

Left-aligns the value in a field of a given width.

Argument: field size

For example:

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

If value is Django, the output will be "Django    ".

lower

Converts a string into all lowercase.

For example:

{{ value|lower }}

If value is Still MAD At Yoko, the output will be still mad at yoko.

make_list

Returns the value turned into a list. For a string, it’s a list of characters. For an integer, the argument is cast into an unicode string before creating a list.

For example:

{{ value|make_list }}

If value is the string "Joel", the output would be the list ['J', 'o', 'e', 'l']. If value is 123, the output will be the list ['1', '2', '3'].

phone2numeric

Converts a phone number (possibly containing letters) to its numerical equivalent.

The input doesn’t have to be a valid phone number. This will happily convert any string.

For example:

{{ value|phone2numeric }}

If value is 800-COLLECT, the output will be 800-2655328.

pluralize

如果值不是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" }}.

注意

使用blocktrans来翻译复数形式的字符串

pprint

A wrapper around pprint.pprint() – for debugging, really.

random

Returns a random item from the given list.

For example:

{{ value|random }}

If value is the list ['a', 'b', 'c', 'd'], the output could be "b".

removetags

Deprecated since version 1.8: removetags cannot guarantee HTML safe output and has been deprecated due to security concerns. Consider using bleach instead.

Removes a space-separated list of [X]HTML tags from the output.

For example:

{{ value|removetags:"b span" }}

If value is "<b>Joel</b> <button>is</button> a <span>slug</span>" the unescaped output will be "Joel <button>is</button> a slug".

Note that this filter is case-sensitive.

If value is "<B>Joel</B> <button>is</button> a <span>slug</span>" the unescaped output will be "<B>Joel</B> <button>is</button> a slug".

No safety guarantee

Note that removetags doesn’t give any guarantee about its output being HTML safe. In particular, it doesn’t work recursively, so an input like "<sc<script>ript>alert('XSS')</sc</script>ript>" won’t be safe even if you apply |removetags:"script". So if the input is user provided, NEVER apply the safe filter to a removetags output. If you are looking for something more robust, you can use the bleach Python library, notably its clean method.

rjust

Right-aligns the value in a field of a given width.

Argument: field size

For example:

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

If value is Django, the output will be "    Django".

safe

Marks a string as not requiring further HTML escaping prior to output. When autoescaping is off, this filter has no effect.

Note

If you are chaining filters, a filter applied after safe can make the contents unsafe again. For example, the following code prints the variable as is, unescaped:

{{ var|safe|escape }}

safeseq

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

{{ some_list|safeseq|join:", " }}

You couldn’t use the safe filter directly in this case, as it would first convert the variable into a string, rather than working with the individual elements of the sequence.

slice

Returns a slice of the list.

Uses the same syntax as Python’s list slicing. See http://www.diveintopython3.net/native-datatypes.html#slicinglists for an introduction.

Example:

{{ some_list|slice:":2" }}

If some_list is ['a', 'b', 'c'], the output will be ['a', 'b'].

slugify

Converts to ASCII. Converts spaces to hyphens. Removes characters that aren’t alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace.

For example:

{{ value|slugify }}

If value is "Joel is a slug", the output will be "joel-is-a-slug".

stringformat

Formats the variable according to the argument, a string formatting specifier. This specifier uses Python string formatting syntax, with the exception that the leading “%” is dropped.

See https://docs.python.org/library/stdtypes.html#string-formatting-operations for documentation of Python string formatting

For example:

{{ value|stringformat:"E" }}

If value is 10, the output will be 1.000000E+01.

striptags

Makes all possible efforts to strip all [X]HTML tags.

For example:

{{ value|striptags }}

If value is "<b>Joel</b> <button>is</button> a <span>slug</span>", the output will be "Joel is a slug".

No safety guarantee

Note that striptags doesn’t give any guarantee about its output being HTML safe, particularly with non valid HTML input. So NEVER apply the safe filter to a striptags output. 如果您正在寻找更强大的功能,可以使用bleach Python库,特别是其clean方法。

time

Formats a time according to the given format.

Given format can be the predefined one TIME_FORMAT, or a custom format, same as the date filter. Note that the predefined format is locale-dependent.

For example:

{{ value|time:"H:i" }}

If value is equivalent to datetime.datetime.now(), the output will be the string "01:23".

Another example:

Assuming that USE_L10N is True and LANGUAGE_CODE is, for example, "de", then for:

{{ value|time:"TIME_FORMAT" }}

the output will be the string "01:23:00" (The "TIME_FORMAT" format specifier for the de locale as shipped with Django is "H:i:s").

The time filter will only accept parameters in the format string that relate to the time of day, not the date (for obvious reasons). If you need to format a date value, use the date filter instead (or along time if you need to render a full datetime value).

There is one exception the above rule: When passed a datetime value with attached timezone information (a time-zone-aware datetime instance) the time filter will accept the timezone-related format specifiers 'e', 'O' , 'T' and 'Z'.

When used without a format string:

{{ value|time }}

...the formatting string defined in the TIME_FORMAT setting will be used, without applying any localization.

Changed in Django 1.7:

The ability to receive and act on values with attached timezone information was added in Django 1.7.

timesince

Formats a date as the time since that date (e.g., “4 days, 6 hours”).

Takes an optional argument that is a variable containing the date to use as the comparison point (without the argument, the comparison point is now). For example, if blog_date is a date instance representing midnight on 1 June 2006, and comment_date is a date instance for 08:00 on 1 June 2006, then the following would return “8 hours”:

{{ blog_date|timesince:comment_date }}

Comparing offset-naive and offset-aware datetimes will return an empty string.

Minutes is the smallest unit used, and “0 minutes” will be returned for any date that is in the future relative to the comparison point.

timeuntil

Similar to timesince, except that it measures the time from now until the given date or datetime. For example, if today is 1 June 2006 and conference_date is a date instance holding 29 June 2006, then {{ conference_date|timeuntil }} will return “4 weeks”.

Takes an optional argument that is a variable containing the date to use as the comparison point (instead of now). If from_date contains 22 June 2006, then the following will return “1 week”:

{{ conference_date|timeuntil:from_date }}

Comparing offset-naive and offset-aware datetimes will return an empty string.

Minutes is the smallest unit used, and “0 minutes” will be returned for any date that is in the past relative to the comparison point.

title

Converts a string into titlecase by making words start with an uppercase character and the remaining characters lowercase. This tag makes no effort to keep “trivial words” in lowercase.

For example:

{{ value|title }}

如果value“my FIRST post”,输出将为“My First Post”

truncatechars

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

Argument: 要截断的字符数

For example:

{{ value|truncatechars:9 }}

If value is "Joel is a slug", the output will be "Joel i...".

truncatechars_html

New in Django 1.7.

Similar to truncatechars, except that it is aware of HTML tags. Any tags that are opened in the string and not closed before the truncation point are closed immediately after the truncation.

例如:

{{ value|truncatechars_html:9 }}

If value is "<p>Joel is a slug</p>", the output will be "<p>Joel i...</p>".

Newlines in the HTML content will be preserved.

truncatewords

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

Argument: 要截断的字数

例如:

{{ value|truncatewords:2 }}

如果value"Joel is a slug", 输出变为 "Joel is ...".

字符串中的换行符将被删除。

truncatewords_html

Similar to truncatewords, except that it is aware of HTML tags. Any tags that are opened in the string and not closed before the truncation point, are closed immediately after the truncation.

This is less efficient than truncatewords, so should only be used when it is being passed HTML text.

For example:

{{ value|truncatewords_html:2 }}

If value is "<p>Joel is a slug</p>", the output will be "<p>Joel is ...</p>".

Newlines in the HTML content will be preserved.

unordered_list

接收一个嵌套的列表,返回一个HTML 的列表 —— 不包含开始和结束的<ul> 标签。

列表假设成具有合法的格式。例如,如果var 包含['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']], 那么{{ var|unordered_list }} 将返回:

<li>States
<ul>
        <li>Kansas
        <ul>
                <li>Lawrence</li>
                <li>Topeka</li>
        </ul>
        </li>
        <li>Illinois</li>
</ul>
</li>

Deprecated since version 1.8: An older, more restrictive and verbose input format is also supported: ['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]. 这种语法在Django 2.0 中将不再支持。

upper

将字符串转换为大写形式:

For example:

{{ value|upper }}

If value is "Joel is a slug", the output will be "JOEL IS A SLUG".

urlencode

Escapes a value for use in a URL.

For example:

{{ value|urlencode }}

If value is "http://www.example.org/foo?a=b&c=d", the output will be "http%3A//www.example.org/foo%3Fa%3Db%26c%3Dd".

可以提供包含不应该转义的字符的可选参数。

If not provided, the ‘/’ character is assumed safe. 所有字符应该转义时,可以提供空字符串。For example:

{{ value|urlencode:"" }}

If value is "http://www.example.org/", the output will be "http%3A%2F%2Fwww.example.org%2F".

urlize

将文字中的网址和电子邮件地址转换为可点击的链接。

This template tag works on links prefixed with http://, https://, or www.. For example, http://goo.gl/aia1t will get converted but goo.gl/aia1t won’t.

It also supports domain-only links ending in one of the original top level domains (.com, .edu, .gov, .int, .mil, .net, and .org). For example, djangoproject.com gets converted.

Changed in Django 1.8:

Support for domain-only links that include characters after the top-level domain (e.g. djangoproject.com/ and djangoproject.com/download/) was added.

链接可以具有结尾标点符号(句点,逗号,近括号)和前导标点符号(开头括号),urlize仍然可以做正确的事。

Links generated by urlize have a rel="nofollow" attribute added to them.

For example:

{{ value|urlize }}

If value is "Check out www.djangoproject.com", the output will be "Check out <a href="http://www.djangoproject.com" rel="nofollow">www.djangoproject.com</a>".

In addition to web links, urlize also converts email addresses into mailto: links. If value is "Send questions to foo@example.com", the output will be "Send questions to <a href="mailto:foo@example.com">foo@example.com</a>".

The urlize filter also takes an optional parameter autoescape. If autoescape is True, the link text and URLs will be escaped using Django’s built-in escape filter. The default value for autoescape is True.

Note

If urlize is applied to text that already contains HTML markup, things won’t work as expected. Apply this filter only to plain text.

urlizetrunc

Converts URLs and email addresses into clickable links just like urlize, but truncates URLs longer than the given character limit.

Argument: Number of characters that link text should be truncated to, including the ellipsis that’s added if truncation is necessary.

For example:

{{ value|urlizetrunc:15 }}

If value is "Check out www.djangoproject.com", the output would be 'Check out <a href="http://www.djangoproject.com" rel="nofollow">www.djangopr...</a>'.

As with urlize, this filter should only be applied to plain text.

wordcount

Returns the number of words.

For example:

{{ value|wordcount }}

If value is "Joel is a slug", the output will be 4.

wordwrap

Wraps words at specified line length.

Argument: number of characters at which to wrap the text

For example:

{{ value|wordwrap:5 }}

如果valueJoel is a slug 输出将是:

Joel
is a
slug

yesno

Maps values for True, False, and (optionally) None, to the strings “yes”, “no”, “maybe”, or a custom mapping passed as a comma-separated list, and returns one of those strings according to the value:

例如:

{{ value|yesno:"yeah,no,maybe" }}
Value Argument Outputs
True   yes
True "yeah,no,maybe" yeah
False "yeah,no,maybe" no
None "yeah,no,maybe" maybe
None "yeah,no" no (converts None to False if no mapping for None is given)

Internationalization tags and filters

Django provides template tags and filters to control each aspect of internationalization in templates. They allow for granular control of translations, formatting, and time zone conversions.

i18n

This library allows specifying translatable text in templates. 要启用它,请将USE_I18N设置为True,然后加载{% load i18n %}

See Internationalization: in template code.

l10n

This library provides control over the localization of values in templates. 您只需要使用{% load l10n %}但您通常会将USE_L10N设置为True,以便本地化默认处于活动状态。

See Controlling localization in templates.

tz

This library provides control over time zone conversions in templates. l10n,您只需要使用{% load tz },但通常还会将USE_TZ设置为True,以便默认情况下会转换为本地时间。

See Time zone aware output in templates.

Other tags and filters libraries

Django comes with a couple of other template-tag libraries that you have to enable explicitly in your INSTALLED_APPS setting and enable in your template with the {% load %} tag.

django.contrib.humanize

A set of Django template filters useful for adding a “human touch” to data. See django.contrib.humanize.

django.contrib.webdesign

A collection of template tags that can be useful while designing a Web site, such as a generator of Lorem Ipsum text. See django.contrib.webdesign.

static

static

To link to static files that are saved in STATIC_ROOT Django ships with a static template tag. You can use this regardless if you’re using RequestContext or not.

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

It is also able to consume standard context variables, e.g. assuming a user_stylesheet variable is passed to the template:

{% load static %}
<link rel="stylesheet" href="{% static user_stylesheet %}" type="text/css" media="screen" />

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

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

Note

The staticfiles contrib app also ships with a static template tag which uses staticfiles' STATICFILES_STORAGE to build the URL of the given path (rather than simply using urllib.parse.urljoin() with the STATIC_URL setting and the given path). Use that instead if you have an advanced use case such as using a cloud service to serve static files:

{% load static from staticfiles %}
<img src="{% static "images/hi.jpg" %}" alt="Hi!" />

get_static_prefix

您应该选择static静态模板标记, 但如果需要对 STATIC_URL 在模板中的确切位置和方式进行更多的控制, 则可以使用 get_static_prefix 模板标记:

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

There’s also a second form you can use to avoid extra processing if you need the value multiple times:

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

get_media_prefix

Similar to the get_static_prefix, get_media_prefix populates a template variable with the media prefix MEDIA_URL, e.g.:

{% load static %}
<body data-media-url="{% get_media_prefix %}">

By storing the value in a data attribute, we ensure it’s escaped appropriately if we want to use it in a JavaScript context.