Built-in template tags and filters

此文档介绍了 Django 内建的模板标签和过滤器. 在此建议您使用 自动化文档, 如果他是可用的, 那么他还包含了自定义的模板标签和过滤器.

内建标签参考

autoescape

控制当前使用的自动转义行为. 这个标签带有 onoff 参数, 决定了块内是否自动转义. 该块由 endautoescape 标签结束.

当自动转义是生效的, 所有变量的内容将被自动转义成HTML字面值后输出(在这之前,其他的过滤器均被执行). 这等效于在所有变量上应用了 escape 过滤器.

唯一的例外是已被标记为”安全”的转义, 如由代码生成的变量, 或使用了 safe , escape 过滤器.

简单的应用:

  1. {% autoescape on %}
  2. {{ body }}
  3. {% endautoescape %}

block

定义一个块, 可以被子模板覆盖. 参见 模板继承.

comment

Ignores everything between {% comment %} and {% endcomment %}. An optional note may be inserted in the first tag. For example, this is useful when commenting out code for documenting why the code was disabled.

简单的应用:

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

comment tags cannot be nested.

csrf_token

This tag is used for CSRF protection, as described in the documentation for Cross Site Request Forgeries.

cycle

Produces one of its arguments each time this tag is encountered. The first argument is produced on the first encounter, the second argument on the second encounter, and so forth. Once all arguments are exhausted, the tag cycles to the first argument and produces it again.

This tag is particularly useful in a loop:

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

The first iteration produces HTML that refers to class row1, the second to row2, the third to row1 again, and so on for each iteration of the loop.

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

  1. {% for o in some_list %}
  2. <tr class="{% cycle rowvalue1 rowvalue2 %}">
  3. ...
  4. </tr>
  5. {% endfor %}

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

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

您可以混合使用变量和字符串:

  1. {% for o in some_list %}
  2. <tr class="{% cycle 'row1' rowvalue2 'row3' %}">
  3. ...
  4. </tr>
  5. {% 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:

  1. {% 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:

  1. <tr>
  2. <td class="{% cycle 'row1' 'row2' as rowcolors %}">...</td>
  3. <td class="{{ rowcolors }}">...</td>
  4. </tr>
  5. <tr>
  6. <td class="{% cycle rowcolors %}">...</td>
  7. <td class="{{ rowcolors }}">...</td>
  8. </tr>

将会输出:

  1. <tr>
  2. <td class="row1">...</td>
  3. <td class="row1">...</td>
  4. </tr>
  5. <tr>
  6. <td class="row2">...</td>
  7. <td class="row2">...</td>
  8. </tr>

You can use any number of values in a cycle tag, separated by spaces. Values enclosed in single quotes (') or double quotes (") are treated as string literals, while values without quotes are treated as template variables.

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:

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

This will output a list of <tr> elements with class alternating between row1 and row2. The subtemplate will have access to rowcolors in its context and the value will match the class of the <tr> that encloses it. If the silent keyword were to be omitted, row1 and row2 would be emitted as normal text, outside the <tr> element.

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:

  1. {% cycle 'row1' 'row2' as rowcolors silent %}
  2. {% cycle rowcolors %}

You can use the resetcycle tag to make a {% cycle %} tag restart from its first value when it’s next encountered.

debug

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

extends

标记此模板继承的父模板的标签.

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

  • {% extends "base.html" %} (使用引号) Django将使用字面值 "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:

  1. dir1/
  2. template.html
  3. base2.html
  4. my/
  5. base3.html
  6. base1.html

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

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

filter

Filters the contents of the block through one or more filters. Multiple filters can be specified with pipes and filters can have arguments, just as in variable syntax.

Note that the block includes all the text between the filter and endfilter tags.

简单的应用:

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

注解

The escape and safe filters are not acceptable arguments. Instead, use the autoescape tag to manage autoescaping for blocks of template code.

firstof

Outputs the first argument variable that is not “false” (i.e. exists, is not empty, is not a false boolean value, and is not a zero numeric value). Outputs nothing if all the passed variables are “false”.

简单的应用:

  1. {% firstof var1 var2 var3 %}

This is equivalent to:

  1. {% if var1 %}
  2. {{ var1 }}
  3. {% elif var2 %}
  4. {{ var2 }}
  5. {% elif var3 %}
  6. {{ var3 }}
  7. {% endif %}

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

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

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

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

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

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

You can use the syntax {% firstof var1 var2 var3 as value %} to store the output inside a variable.

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:

  1. <ul>
  2. {% for athlete in athlete_list %}
  3. <li>{{ athlete.name }}</li>
  4. {% endfor %}
  5. </ul>

You can loop over a list in reverse by using {% 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:

  1. {% for x, y in points %}
  2. There is a point at {{ x }},{{ y }}
  3. {% 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:

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

Keep in mind that for the dot operator, dictionary key lookup takes precedence over method lookup. Therefore if the data dictionary contains a key named 'items', data.items will return data['items'] instead of data.items(). Avoid adding keys that are named like dictionary methods if you want to use those methods in a template (items, values, keys, etc.). Read more about the lookup order of the dot operator in the documentation of template variables.

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

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

forempty

当传递到 for 标签中的数组不存在或为空时,可以使用 {% empty %} 标签来指定输出的内容:

  1. <ul>
  2. {% for athlete in athlete_list %}
  3. <li>{{ athlete.name }}</li>
  4. {% empty %}
  5. <li>Sorry, no athletes in this list.</li>
  6. {% endfor %}
  7. </ul>

上面的代码与下面的代码是等同的,但上面的代码更简短,更清晰,也可能更快。

  1. <ul>
  2. {% if athlete_list %}
  3. {% for athlete in athlete_list %}
  4. <li>{{ athlete.name }}</li>
  5. {% endfor %}
  6. {% else %}
  7. <li>Sorry, no athletes in this list.</li>
  8. {% endif %}
  9. </ul>

if

{% if %} 标签会判断给定的变量,当变量为True时(比如存在、非空、非布尔值False),就会输出块内的内容:

  1. {% if athlete_list %}
  2. Number of athletes: {{ athlete_list|length }}
  3. {% elif athlete_in_locker_room_list %}
  4. Athletes should be out of the locker room soon!
  5. {% else %}
  6. No athletes.
  7. {% 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:

  1. {% if athlete_list and coach_list %}
  2. Both athletes and coaches are available.
  3. {% endif %}
  4. {% if not athlete_list %}
  5. There are no athletes.
  6. {% endif %}
  7. {% if athlete_list or coach_list %}
  8. There are some athletes or some coaches.
  9. {% endif %}
  10. {% if not athlete_list or coach_list %}
  11. There are no athletes or there are some coaches.
  12. {% endif %}
  13. {% if athlete_list and not coach_list %}
  14. There are some athletes and absolutely no coaches.
  15. {% endif %}

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

  1. {% if athlete_list and coach_list or cheerleader_list %}

will be interpreted like:

  1. if (athlete_list and coach_list) or cheerleader_list

Use of actual parentheses in the if tag is invalid syntax. If you need them to indicate precedence, you should use nested if tags.

if tags may also use the operators ==, !=, <, >, <=, >=, in, not in, is, and is not which work as follows:

== operator

Equality. Example:

  1. {% if somevar == "x" %}
  2. This appears if variable somevar equals the string "x"
  3. {% endif %}
!= operator

Inequality. Example:

  1. {% if somevar != "x" %}
  2. This appears if variable somevar does not equal the string "x",
  3. or if somevar is not found in the context
  4. {% endif %}
< operator

Less than. Example:

  1. {% if somevar < 100 %}
  2. This appears if variable somevar is less than 100.
  3. {% endif %}
> operator

Greater than. Example:

  1. {% if somevar > 0 %}
  2. This appears if variable somevar is greater than 0.
  3. {% endif %}
<= operator

Less than or equal to. Example:

  1. {% if somevar <= 100 %}
  2. This appears if variable somevar is less than 100 or equal to 100.
  3. {% endif %}
>= operator

Greater than or equal to. Example:

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

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:

  1. {% if "bc" in "abcdef" %}
  2. This appears since "bc" is a substring of "abcdef"
  3. {% endif %}
  4. {% if "hello" in greetings %}
  5. If greetings is a list or set, one element of which is the string
  6. "hello", this will appear.
  7. {% endif %}
  8. {% if user in users %}
  9. If users is a QuerySet, this will appear if user is an
  10. instance that belongs to the QuerySet.
  11. {% endif %}
not in operator

Not contained within. This is the negation of the in operator.

is operator

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

  1. {% if somevar is True %}
  2. This appears if and only if somevar is True.
  3. {% endif %}
  4. {% if somevar is None %}
  5. This appears if somevar is None, or if somevar is not found in the context.
  6. {% endif %}
is not operator

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

  1. {% if somevar is not True %}
  2. This appears if somevar is not True, or if somevar is not found in the
  3. context.
  4. {% endif %}
  5. {% if somevar is not None %}
  6. This appears if and only if somevar is not None.
  7. {% endif %}

过滤器

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

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

Complex expressions

All of the above can be combined to form complex expressions. For such expressions, it can be important to know how the operators are grouped when the expression is evaluated - that is, the precedence rules. The precedence of the operators, from lowest to highest, is as follows:

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

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

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

…will be interpreted as:

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

If you need different precedence, you will need to use nested if tags. Sometimes that is better for clarity anyway, for the sake of those who do not know the precedence rules.

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

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

you should use:

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

ifequal and ifnotequal

3.1 版后已移除.

{% ifequal a b %} ... {% endifequal %} is an obsolete way to write {% if a == b %} ... {% endif %}. Likewise, {% ifnotequal a b %} ... {% endifnotequal %} is superseded by {% if a != b %} ... {% endif %}.

ifchanged

Check if a value has changed from the last iteration of a loop.

The {% ifchanged %} block tag is used within a loop. It has two possible uses.

  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:

    1. <h1>Archive for {{ year }}</h1>
    2. {% for date in days %}
    3. {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
    4. <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
    5. {% endfor %}
  2. 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:

    1. {% for date in days %}
    2. {% ifchanged date.date %} {{ date.date }} {% endifchanged %}
    3. {% ifchanged date.hour date.date %}
    4. {{ date.hour }}
    5. {% endifchanged %}
    6. {% endfor %}

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

  1. {% for match in matches %}
  2. <div style="background-color:
  3. {% ifchanged match.ballot_id %}
  4. {% cycle "red" "blue" %}
  5. {% else %}
  6. gray
  7. {% endifchanged %}
  8. ">{{ match }}</div>
  9. {% endfor %}

include

Loads a template and renders it with the current context. This is a way of “including” other templates within a template.

The template name can either be a variable or a hard-coded (quoted) string, in either single or double quotes.

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

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

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 ../ as described in the extends tag.

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

  1. {% include template_name %}

The variable may also be any object with a render() method that accepts a context. This allows you to reference a compiled Template in your context.

Additionally, the variable may be an iterable of template names, in which case the first that can be loaded will be used, as per select_template().

An included template is rendered within the context of the template that includes it. This example produces the output "Hello, John!":

  • Context: variable person is set to "John" and variable greeting is set to "Hello".

  • Template:

    1. {% include "name_snippet.html" %}
  • The name_snippet.html template:

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

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

  1. {% 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:

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

注解

The include tag should be considered as an implementation of “render this subtemplate and include the HTML”, not as “parse this subtemplate and include its contents as if it were part of the parent”. This means that there is no shared state between included templates — each include is a completely independent rendering process.

Blocks are evaluated before they are included. This means that a template that includes blocks from another will contain blocks that have already been evaluated and rendered - not blocks that can be overridden by, for example, an extending template.

Changed in Django 3.1:

Support for iterables of template names was added.

load

Loads a custom template tag set.

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

  1. {% 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:

  1. {% load foo bar from somelibrary %}

See Custom tag and filter libraries for more information.

lorem

Displays random “lorem ipsum” Latin text. This is useful for providing sample data in templates.

Usage:

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

The {% lorem %} tag can be used with zero, one, two or three arguments. The arguments are:

Argument描述
countA number (or variable) containing the number of paragraphs or words to generate (default is 1).
methodEither w for words, p for HTML paragraphs or b for plain-text paragraph blocks (default is b).
randomThe word random, which if given, does not use the common paragraph (“Lorem ipsum dolor sit amet…”) when generating text.

Examples:

  • {% lorem %} will output the common “lorem ipsum” paragraph.
  • {% 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

Displays the current date and/or time, using a format according to the given string. Such string can contain format specifiers characters as described in the date filter section.

举例:

  1. 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:

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

This would display as “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.:

  1. 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:

  1. {% now "Y" as current_year %}
  2. {% blocktranslate %}Copyright {{ current_year }}{% endblocktranslate %}

regroup

Regroups a list of alike objects by a common attribute.

This complex tag is best illustrated by way of an example: say that cities is a list of cities represented by dictionaries containing "name", "population", and "country" keys:

  1. cities = [
  2. {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
  3. {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
  4. {'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
  5. {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
  6. {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
  7. ]

…and you’d like to display a hierarchical list that is ordered by country, like this:

  • 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:

  1. {% regroup cities by country as country_list %}
  2. <ul>
  3. {% for country in country_list %}
  4. <li>{{ country.grouper }}
  5. <ul>
  6. {% for city in country.list %}
  7. <li>{{ city.name }}: {{ city.population }}</li>
  8. {% endfor %}
  9. </ul>
  10. </li>
  11. {% endfor %}
  12. </ul>

Let’s walk through this example. {% regroup %} takes three arguments: the list you want to regroup, the attribute to group by, and the name of the resulting list. 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. Group objects are instances of namedtuple() with two fields:

  • 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’).

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

  1. {% regroup cities by country as country_list %}
  2. <ul>
  3. {% for country, local_cities in country_list %}
  4. <li>{{ country }}
  5. <ul>
  6. {% for city in local_cities %}
  7. <li>{{ city.name }}: {{ city.population }}</li>
  8. {% endfor %}
  9. </ul>
  10. </li>
  11. {% endfor %}
  12. </ul>

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):

  1. cities = [
  2. {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
  3. {'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
  4. {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
  5. {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
  6. {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
  7. ]

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:

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

Grouping on other properties

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:

  1. {% 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:

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

resetcycle

Resets a previous cycle so that it restarts from its first item at its next encounter. Without arguments, {% resetcycle %} will reset the last {% cycle %} defined in the template.

用法示例:

  1. {% for coach in coach_list %}
  2. <h1>{{ coach.name }}</h1>
  3. {% for athlete in coach.athlete_set.all %}
  4. <p class="{% cycle 'odd' 'even' %}">{{ athlete.name }}</p>
  5. {% endfor %}
  6. {% resetcycle %}
  7. {% endfor %}

This example would return this HTML:

  1. <h1>José Mourinho</h1>
  2. <p class="odd">Thibaut Courtois</p>
  3. <p class="even">John Terry</p>
  4. <p class="odd">Eden Hazard</p>
  5. <h1>Carlo Ancelotti</h1>
  6. <p class="odd">Manuel Neuer</p>
  7. <p class="even">Thomas Müller</p>

Notice how the first block ends with class="odd" and the new one starts with class="odd". Without the {% resetcycle %} tag, the second block would start with class="even".

You can also reset named cycle tags:

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

In this example, we have both the alternating odd/even rows and a “major” row every fifth row. Only the five-row cycle is reset when a category changes.

spaceless

Removes whitespace between HTML tags. This includes tab characters and newlines.

用法示例:

  1. {% spaceless %}
  2. <p>
  3. <a href="foo/">Foo</a>
  4. </p>
  5. {% endspaceless %}

This example would return this HTML:

  1. <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:

  1. {% spaceless %}
  2. <strong>
  3. Hello
  4. </strong>
  5. {% endspaceless %}

templatetag

Outputs one of the syntax characters used to compose template tags.

Since the template system has no concept of “escaping”, to display one of the bits used in template tags, you must use the {% templatetag %} tag.

The argument tells which template bit to output:

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

简单的应用:

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

url

Returns an absolute path reference (a URL without the domain name) matching a given view and optional parameters. Any special characters in the resulting path will be encoded using iri_to_uri().

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

  1. {% 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:

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

Do not mix both positional and keyword syntax in a single call. All arguments required by the URLconf should be present.

For example, suppose you have a view, app_views.client, whose URLconf takes a client ID (here, client() is a method inside the views file app_views.py). The URLconf line might look like this:

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

If this app’s URLconf is included into the project’s URLconf under a path such as this:

  1. path('clients/', include('project_name.app_name.urls'))

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

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

The template tag will output the string /clients/client/123/.

Note that if the URL you’re reversing doesn’t exist, you’ll get an NoReverseMatch exception raised, which will cause your site to display an error page.

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

  1. {% url 'some-url-name' arg arg2 as the_url %}
  2. <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.

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:

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

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

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

This will follow the normal namespaced URL resolution strategy, including using any hints provided by the context as to the current application.

警告

Don’t forget to put quotes around the URL pattern name, otherwise the value will be interpreted as a context variable!

verbatim

Stops the template engine from rendering the contents of this block tag.

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

  1. {% verbatim %}
  2. {{if dying}}Still alive.{{/if}}
  3. {% endverbatim %}

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

  1. {% verbatim myblock %}
  2. Avoid template rendering via the {% verbatim %}{% endverbatim %} block.
  3. {% 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.

例子:

  1. <img src="bar.png" alt="Bar"
  2. 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 blocktranslate like this:

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

with

Caches a complex variable under a simpler name. This is useful when accessing an “expensive” method (e.g., one that hits the database) multiple times.

例子:

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

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

You can assign more than one context variable:

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

注解

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

Built-in filter reference

add

Adds the argument to the value.

例子:

  1. {{ value|add:"2" }}

If value is 4, then the output will be 6.

This filter will first try to coerce both values to integers. If this fails, it’ll attempt to add the values together anyway. This will work on some data types (strings, list, etc.) and fail on others. If it fails, the result will be an empty string.

For example, if we have:

  1. {{ first|add:second }}

and first is [1, 2, 3] and second is [4, 5, 6], then the output will be [1, 2, 3, 4, 5, 6].

警告

Strings that can be coerced to integers will be summed, not concatenated, as in the first example above.

addslashes

Adds slashes before quotes. Useful for escaping strings in CSV, for example.

例子:

  1. {{ value|addslashes }}

If value is "I'm using Django", the output will be "I\'m using Django".

capfirst

Capitalizes the first character of the value. If the first character is not a letter, this filter has no effect.

例子:

  1. {{ value|capfirst }}

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

center

Centers the value in a field of a given width.

例子:

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

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

cut

Removes all values of arg from the given string.

例子:

  1. {{ value|cut:" " }}

If value is "String with spaces", the output will be "Stringwithspaces".

date

Formats a date according to the given format.

Uses a similar format as PHP’s date() function (https://php.net/date) with some differences.

注解

These format characters are not used in Django outside of templates. They were designed to be compatible with PHP to ease transitioning for designers.

Available format strings:

Format character描述Example output
Day  
dDay of the month, 2 digits with leading zeros.‘01’ to ‘31’
jDay of the month without leading zeros.‘1’ to ‘31’
DDay of the week, textual, 3 letters.‘Fri’
lDay of the week, textual, long.‘Friday’
SEnglish ordinal suffix for day of the month, 2 characters.‘st’, ‘nd’, ‘rd’ or ‘th’
wDay of the week, digits without leading zeros.‘0’ (Sunday) to ‘6’ (Saturday)
zDay of the year.1 to 366
Week  
WISO-8601 week number of year, with weeks starting on Monday.1, 53
Month  
mMonth, 2 digits with leading zeros.‘01’ to ‘12’
nMonth without leading zeros.‘1’ to ‘12’
MMonth, textual, 3 letters.‘Jan’
bMonth, textual, 3 letters, lowercase.‘jan’
EMonth, locale specific alternative representation usually used for long date representation.‘listopada’ (for Polish locale, as opposed to ‘Listopad’)
FMonth, textual, long.‘January’
NMonth abbreviation in Associated Press style. Proprietary extension.‘Jan.’, ‘Feb.’, ‘March’, ‘May’
tNumber of days in the given month.28 to 31
Year  
yYear, 2 digits.‘99’
YYear, 4 digits.‘1999’
LBoolean for whether it’s a leap year.True or False
oISO-8601 week-numbering year, corresponding to the ISO-8601 week number (W) which uses leap weeks. See Y for the more common year format.‘1999’
Time  
gHour, 12-hour format without leading zeros.‘1’ to ‘12’
GHour, 24-hour format without leading zeros.‘0’ to ‘23’
hHour, 12-hour format.‘01’ to ‘12’
HHour, 24-hour format.‘00’ to ‘23’
iMinutes.‘00’ to ‘59’
sSeconds, 2 digits with leading zeros.‘00’ to ‘59’
uMicroseconds.000000 to 999999
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’
fTime, in 12-hour hours and minutes, with minutes left off if they’re zero. Proprietary extension.‘1’, ‘1:30’
PTime, 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.’
Timezone  
eTimezone name. Could be in any format, or might return an empty string, depending on the datetime.‘’, ‘GMT’, ‘-500’, ‘US/Eastern’, etc.
IDaylight Savings Time, whether it’s in effect or not.‘1’ or ‘0’
ODifference to Greenwich time in hours.‘+0200’
TTime zone of this machine.‘EST’, ‘MDT’
ZTime 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
Date/Time  
cISO 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
rRFC 5322 formatted date.‘Thu, 21 Dec 2000 16:01:07 +0200’
USeconds since the Unix Epoch (January 1 1970 00:00:00 UTC). 

例子:

  1. {{ 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:

  1. {{ 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, the DATE_FORMAT format specifier is used. Assuming the same settings as the previous example:

  1. {{ value|date }}

outputs 9 de Enero de 2008 (the DATE_FORMAT format specifier for the es locale is r'j \d\e F \d\e Y'). Both “d” and “e” are backslash-escaped, because otherwise each is a format string that displays the day and the timezone name, respectively.

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

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

default

If value evaluates to False, uses the given default. Otherwise, uses the value.

例子:

  1. {{ value|default:"nothing" }}

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

default_if_none

If (and only if) value is None, uses the given default. Otherwise, uses the value.

Note that if an empty string is given, the default value will not be used. Use the default filter if you want to fallback for empty strings.

例子:

  1. {{ value|default_if_none:"nothing" }}

If value is None, the output will be nothing.

dictsort

Takes a list of dictionaries and returns that list sorted by the key given in the argument.

例子:

  1. {{ value|dictsort:"name" }}

If value is:

  1. [
  2. {'name': 'zed', 'age': 19},
  3. {'name': 'amy', 'age': 22},
  4. {'name': 'joe', 'age': 31},
  5. ]

then the output would be:

  1. [
  2. {'name': 'amy', 'age': 22},
  3. {'name': 'joe', 'age': 31},
  4. {'name': 'zed', 'age': 19},
  5. ]

You can also do more complicated things like:

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

If books is:

  1. [
  2. {'title': '1984', 'author': {'name': 'George', 'age': 45}},
  3. {'title': 'Timequake', 'author': {'name': 'Kurt', 'age': 75}},
  4. {'title': 'Alice', 'author': {'name': 'Lewis', 'age': 33}},
  5. ]

then the output would be:

  1. * Alice (Lewis)
  2. * 1984 (George)
  3. * Timequake (Kurt)

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

  1. {{ value|dictsort:0 }}

If value is:

  1. [
  2. ('a', '42'),
  3. ('c', 'string'),
  4. ('b', 'foo'),
  5. ]

then the output would be:

  1. [
  2. ('a', '42'),
  3. ('b', 'foo'),
  4. ('c', 'string'),
  5. ]

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

  1. {{ values|dictsort:"0" }}

dictsortreversed

Takes a list of dictionaries and returns that list sorted in reverse order by the key given in the argument. This works exactly the same as the above filter, but the returned value will be in reverse order.

divisibleby

Returns True if the value is divisible by the argument.

例子:

  1. {{ value|divisibleby:"3" }}

If value is 21, the output would be True.

escape

Escapes a string’s HTML. Specifically, it makes these replacements:

  • < 被替换为 &lt;
  • > 被替换为 &gt;
  • ' (single quote) is converted to &#x27;
  • " (双引号) 被替换为 &quot;
  • & 被替换为 &amp;

Applying escape to a variable that would normally have auto-escaping applied to the result will only result in one round of escaping being done. So it is safe to use this function even in auto-escaping environments. If you want multiple escaping passes to be applied, use the force_escape filter.

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

  1. {% autoescape off %}
  2. {{ title|escape }}
  3. {% endautoescape %}

escapejs

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

例子:

  1. {{ 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

Formats the value like a ‘human-readable’ file size (i.e. '13 KB', '4.1 MB', '102 bytes', etc.).

例子:

  1. {{ value|filesizeformat }}

If value is 123456789, the output would be 117.7 MB.

File sizes and SI units

Strictly speaking, filesizeformat does not conform to the International System of Units which recommends using KiB, MiB, GiB, etc. when byte sizes are calculated in powers of 1024 (which is the case here). Instead, Django uses traditional unit names (KB, MB, GB, etc.) corresponding to names that are more commonly used.

first

Returns the first item in a list.

例子:

  1. {{ value|first }}

If value is the list ['a', 'b', 'c'], the output will be '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:

valueTemplateOutput
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:

valueTemplateOutput
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.

valueTemplateOutput
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:

valueTemplateOutput
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.

Changed in Django 3.1:

In older versions, a negative zero -0 was returned for negative numbers which round to zero.

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:

  1. {% autoescape off %}
  2. {{ body|linebreaks|force_escape }}
  3. {% 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.

例子:

  1. {{ 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.

例子:

  1. {{ 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)

例子:

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

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

json_script

Safely outputs a Python object as JSON, wrapped in a <script> tag, ready for use with JavaScript.

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

例子:

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

If value is the dictionary {'hello': 'world'}, the output will be:

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

The resulting data can be accessed in JavaScript like this:

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

XSS attacks are mitigated by escaping the characters “<”, “>” and “&”. For example if value is {'hello': 'world</script>&amp;'}, the output is:

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

This is compatible with a strict Content Security Policy that prohibits in-page script execution. It also maintains a clean separation between passive data and executable code.

last

Returns the last item in a list.

例子:

  1. {{ 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.

例子:

  1. {{ value|length }}

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

The filter returns 0 for an undefined variable.

length_is

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

例子:

  1. {{ 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>).

例子:

  1. {{ value|linebreaks }}

If value is Joel\nis 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>).

例子:

  1. {{ value|linebreaksbr }}

If value is Joel\nis a slug, the output will be Joel<br>is a slug.

linenumbers

Displays text with line numbers.

例子:

  1. {{ value|linenumbers }}

If value is:

  1. one
  2. two
  3. three

the output will be:

  1. 1. one
  2. 2. two
  3. 3. three

ljust

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

Argument: field size

例子:

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

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

lower

Converts a string into all lowercase.

例子:

  1. {{ value|lower }}

If value is Totally LOVING this Album!, the output will be totally loving this album!.

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 to a string before creating a list.

例子:

  1. {{ 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.

例子:

  1. {{ value|phone2numeric }}

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

pluralize

Returns a plural suffix if the value is not 1, '1', or an object of length 1. By default, this suffix is 's'.

举例:

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

If num_messages is 1, the output will be You have 1 message. If num_messages is 2 the output will be You have 2 messages.

For words that require a suffix other than 's', you can provide an alternate suffix as a parameter to the filter.

举例:

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

For words that don’t pluralize by simple suffix, you can specify both a singular and plural suffix, separated by a comma.

举例:

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

注解

Use blocktranslate to pluralize translated strings.

pprint

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

random

Returns a random item from the given list.

例子:

  1. {{ value|random }}

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

rjust

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

Argument: field size

例子:

  1. "{{ 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.

注解

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:

  1. {{ 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:

  1. {{ 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 https://www.diveinto.org/python3/native-datatypes.html#slicinglists for an introduction.

举例:

  1. {{ 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.

例子:

  1. {{ 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 the printf-style String Formatting syntax, with the exception that the leading “%” is dropped.

例子:

  1. {{ 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.

例子:

  1. {{ value|striptags }}

如果 value"<b>Joel</b> <button>is</button> a <span>slug</span>", 那么输出就会是 "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. If you are looking for something more robust, you can use the bleach Python library, notably its clean method.

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.

例子:

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

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

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

  1. {% value|time:"H\h i\m" %}

This would display as “01h 23m”.

Another example:

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

  1. {{ value|time:"TIME_FORMAT" }}

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

The time filter will only accept parameters in the format string that relate to the time of day, not the date. If you need to format a date value, use the date filter instead (or along with 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, the TIME_FORMAT format specifier is used:

  1. {{ value|time }}

is the same as:

  1. {{ value|time:"TIME_FORMAT" }}

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”:

  1. {{ 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”:

  1. {{ 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.

例子:

  1. {{ value|title }}

If value is "my FIRST post", the output will be "My First Post".

truncatechars

Truncates a string if it is longer than the specified number of characters. Truncated strings will end with a translatable ellipsis character (“…”).

Argument: Number of characters to truncate to

例子:

  1. {{ value|truncatechars:7 }}

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

truncatechars_html

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.

例子:

  1. {{ value|truncatechars_html:7 }}

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

Truncates a string after a certain number of words.

Argument: Number of words to truncate after

例子:

  1. {{ value|truncatewords:2 }}

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

Newlines within the string will be removed.

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.

例子:

  1. {{ 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

Recursively takes a self-nested list and returns an HTML unordered list — WITHOUT opening and closing

    tags.

    The list is assumed to be in the proper format. For example, if var contains ['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']], then {{ var|unordered_list }} would return:

    1. <li>States
    2. <ul>
    3. <li>Kansas
    4. <ul>
    5. <li>Lawrence</li>
    6. <li>Topeka</li>
    7. </ul>
    8. </li>
    9. <li>Illinois</li>
    10. </ul>
    11. </li>

    upper

    Converts a string into all uppercase.

    例子:

    1. {{ 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.

    例子:

    1. {{ value|urlencode }}

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

    An optional argument containing the characters which should not be escaped can be provided.

    If not provided, the ‘/‘ character is assumed safe. An empty string can be provided when all characters should be escaped. For example:

    1. {{ value|urlencode:"" }}

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

    urlize

    Converts URLs and email addresses in text into clickable links.

    This template tag works on links prefixed with http://, https://, or www.. For example, https://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.

    Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens), and urlize will still do the right thing.

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

    例子:

    1. {{ 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.

    注解

    If urlize is applied to text that already contains HTML markup, or to email addresses that contain single quotes ('), 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.

    例子:

    1. {{ 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.djangoproj…</a>'.

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

    wordcount

    Returns the number of words.

    例子:

    1. {{ 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

    例子:

    1. {{ value|wordwrap:5 }}

    If value is Joel is a slug, the output would be:

    1. Joel
    2. is a
    3. 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:

    例子:

    1. {{ value|yesno:"yeah,no,maybe" }}
    ValueArgumentOutputs
    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. To enable it, set USE_I18N to True, then load it with {% load i18n %}.

    See 在模板代码中国际化.

    l10n

    This library provides control over the localization of values in templates. You only need to load the library using {% load l10n %}, but you’ll often set USE_L10N to True so that localization is active by default.

    See 在模板中控制本地化.

    tz

    This library provides control over time zone conversions in templates. Like l10n, you only need to load the library using {% load tz %}, but you’ll usually also set USE_TZ to True so that conversion to local time happens by default.

    See 模板中时区感知(aware)输出.

    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.

    static

    static

    To link to static files that are saved in STATIC_ROOT Django ships with a static template tag. If the django.contrib.staticfiles app is installed, the tag will serve files using url() method of the storage specified by STATICFILES_STORAGE. For example:

    1. {% load static %}
    2. <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:

    1. {% load static %}
    2. <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:

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

    使用 Jinja2 模板?

    See Jinja2 for information on using the static tag with Jinja2.

    get_static_prefix

    You should prefer the static template tag, but if you need more control over exactly where and how STATIC_URL is injected into the template, you can use the get_static_prefix template tag:

    1. {% load static %}
    2. <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:

    1. {% load static %}
    2. {% get_static_prefix as STATIC_PREFIX %}
    3. <img src="{{ STATIC_PREFIX }}images/hi.jpg" alt="Hi!">
    4. <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.:

    1. {% load static %}
    2. <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.