首页 > 代码库 > Django1.3 模板标签和过滤器
Django1.3 模板标签和过滤器
内建标签
autoescape
控制HTML转义,参数是:on 或 off。效果和使用safe或escape过滤器相同。
{% autoescape on %} {{ body }} {% endautoescape %}
block
定义一个能被子模板覆盖的区块。
comment
模板引擎会忽略掉 {% comment %} 和 {% endcomment %} 之间的所有内容
csrf_token
防止跨站请求伪造。
<form action="." method="post">{% csrf_token %}
cycle
每次遇到此标签轮流使用给出的字符串或变量的值。
在一个循环内,轮流使用给定的字符串列表的元素:
{% for o in some_list %} <tr class="{% cycle ‘row1‘ ‘row2‘ %}"> ... </tr> {% endfor %}
你也可以使用变量:
{% for o in some_list %} <tr class="{% cycle rowvalue1 rowvalue2 %}"> ... </tr> {% endfor %}
注意到变量的值是没有自动转义的,所以要加上显式转义:
{% for o in some_list %} <tr class="{% filter force_escape %}{% cycle rowvalue1 rowvalue2 %}{% endfilter %}"> ... </tr> {% endfor %}
你可以混合字符串和变量:
{% for o in some_list %} <tr class="{% cycle ‘row1‘ rowvalue2 ‘row3‘ %}"> ... </tr> {% endfor %}
在循环外,在你第一次调用时,给这些字符串定义一个不重复的名字,以后每次只需要使用这个名字就行了:
{% cycle ‘row1‘ ‘row2‘ as rowcolors %}
例:
<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>
输出:
<tr> <td class="row1">...</td> <td class="row1">...</td> </tr> <tr> <td class="row2">...</td> <td class="row2">...</td> </tr>
旧版本是这么写的:
{% cycle row1,row2,row3 %}
如果你只是想声明这个循环,而不是输出循环的值,那么在标签的最后增加关键字silent。例:
{% for obj in some_list %} {% cycle ‘row1‘ ‘row2‘ as rowcolors silent %} <tr class="{{ rowcolors }}">{% include "subtemplate.html " %}</tr> {% endfor %}
一旦你在cycle定义中使用了关键字silent,随后的cycle标签也会自动使用silent。下面的例子什么也不会输出,即使第二次cycle没有指定silent。
{% cycle ‘row1‘ ‘row2‘ as rowcolors silent %} {% cycle rowcolors %}
debug
输出完整的调试信息,包括当前的上下文及导入的模块信息。
extends
标记当前模板扩展一个父模板。
这个标签有两种用法:
- {% extends "base.html" %} (带引号) 直接使用要扩展的父模板的名字 "base.html" .
- {% extends variable %} 用变量 variable 的值来指定父模板。如果变量是一个字符串,Django会把字符串的值当作父模板的文件名。如果变量是一个Template对象,Django会把这个对象当作父模板。
filter
通过可变过滤器过滤变量的内容。
过滤器也可以相互传输,它们也可以有参数,就像变量的语法一样。
例:
{% filter force_escape|lower %} This text will be HTML-escaped, and will appear in all lowercase. {% endfilter %}
注意
escape和safe过滤器不能接受参数,而使用autoescape标签用来管理模板代码块的自动转移。
firstof
输出传入的第一个不是False的变量,如果被传递变量都是False,则什么也不输出。例:
{% firstof var1 var2 var3 %}
等价于:
{% if var1 %} {{ var1|safe }} {% else %}{% if var2 %} {{ var2|safe }} {% else %}{% if var3 %} {{ var3|safe }} {% endif %}{% endif %}{% endif %}
{% firstof var1 var2 var3 "fallback value" %}
{% filter force_escape %} {% firstof var1 var2 var3 "fallback value" %} {% endfilter %}
for
轮询数组中的每一元素。例如显示一个指定的运动员的序列 athlete_list :
<ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} </ul>
你也可以逆向遍历一个列表 {% for obj in list reversed %} 。
如果你循环的是(x,y)坐标的列表,你可以这样:
{% for x, y in points %} There is a point at {{ x }},{{ y }} {% endfor %}
如果你循环的是字典,你可以这样:
{% for key, value in data.items %} {{ key }}: {{ value }} {% endfor %}
for循环设置了许多循环中可用的变量:
变量名 描述forloop.counter | 当前循环次数(索引最小为1)。 |
forloop.counter0 | 当前循环次数 (索引最小为0)。 |
forloop.revcounter | 剩余循环次数 (索引最小为1)。 |
forloop.revcounter0 | 剩余循环次数 (索引最小为0)。 |
forloop.first | 第一次循环时为 True 。 |
forloop.last | 最后一次循环时为 True 。 |
forloop.parentloop | 用于嵌套循环,表示当前循环外层的循环。 |
for ... empty
for标签能使用一个可选的子标签{% empty %} ,表示当循环为空时会被显示:
<ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% empty %} <li>Sorry, no athlete 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 %} 标签测试一个变量,若变量为真(即其存在、非空,且不是一个为假的布尔值),区块中的内容就会被输出:
{% 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 %}
现在新版本支持 {% elif %} 子标签.
Boolean operators
if 语句可使用 and 、 or 和 not 来测试变量或者对给定的变量取反:
{% 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 (OK, so writing English translations of boolean logic sounds stupid; it‘s not our fault). {% endif %} {% if athlete_list and not coach_list %} There are some athletes and absolutely no coaches. {% endif %}
Django新版本支持在同个标签中使用and和or。注意 and比or的优先级更高:
{% if athlete_list and coach_list or cheerleader_list %}
可以这样解释:
if (athlete_list and coach_list) or cheerleader_list
== 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
包含:
{% 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 operator
不包含。
注意:不能这样链式比较:
{% if a > b > c %} (WRONG)
应该这样:
{% if a > b and b > c %}
Filters
你能在if标签中使用过滤器. For example:
{% if messages|length >= 100 %} You have lots of messages today! {% endif %}
Complex expressions
复杂表达式。优先级从低到高:
- or
- and
- not
- in
- ==, !=, <, >, <=, >=
例:
{% if a == b or c == d and e %}
解释成:
(a == b) or ((c == d) and e)
ifchanged
检查循环中一个值从最近一次重复其是否改变。
ifchanged 语句块用于循环中,其作用有两个:
-
它会把要渲染的内容与前一次作比较,发生变化时才显示它。例如,下面要显示一个日期列表,只有月份改变时才会显示它:
<h1>Archive for {{ year }}</h1> {% for date in days %} {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %} <a href=http://www.mamicode.com/"{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a> {% endfor %}
-
如果给的是一个变量,就会检查它是否发生改变。下面例子中日期每次发生变化时就会显示出来,但只有小时和日期都发生变化时才会显示小时。
{% for date in days %} {% ifchanged date.date %} {{ date.date }} {% endifchanged %} {% ifchanged date.hour date.date %} {{ date.hour }} {% endifchanged %} {% endfor %}
ifcahanged标签也可以使用else子标签,当值没有改变时输出:
{% for match in matches %} <div style="background-color: {% ifchanged match.ballot_id %} {% cycle "red" "blue" %} {% else %} grey {% endifchanged %} ">{{ match }}</div> {% endfor %}
ifequal
Output the contents of the block if the two arguments equal each other.
Example:
{% ifequal user.id comment.user_id %} ... {% endifequal %}
As in the if tag, an {% else %} clause is optional.
The arguments can be hard-coded strings, so the following is valid:
{% ifequal user.username "adrian" %} ... {% endifequal %}
It is only possible to compare an argument to template variables or strings. You cannot check for equality with Python objects such as True or False. If you need to test if something is true or false, use the if tag instead.
ifnotequal
Just like ifequal, except it tests that the two arguments are not equal.
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":
{% include "foo/bar.html" %}
This example includes the contents of the template whose name is contained in the variable template_name:
{% include template_name %}
An included template is rendered with the context of the template that‘s including it. This example produces the output"Hello, John":
-
Context: variable person is set to "john".
-
Template:
{% include "name_snippet.html" %}
-
The name_snippet.html template:
{{ greeting }}, {{ person|default:"friend" }}!
You can pass additional context to the template using keyword arguments:
{% include "name_snippet.html" with person="Jane" greeting="Hello" %}
If you want to only render the context with the variables provided (or even no variables at all), use the only option:
{% include "name_snippet.html" with greeting="Hi" only %}
Note
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.
See also: {% ssi %}.
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:
{% load somelibrary package.otherlibrary %}
You can also selectively load individual filters or tags from a library, using the from argument. In this example, the template tags/filters named foo and bar will be loaded from somelibrary:
{% load foo bar from somelibrary %}
See Custom tag and filter libraries for more information.
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.
Example:
It is {% now "jS F Y H:i" %}
Note that you can backslash-escape a format string if you want to use the "raw" value. In this example, "f" is backslash-escaped, because otherwise "f" is a format string that displays the time. The "o" doesn‘t need to be escaped, because it‘s not a format character:
It is the {% now "jS o\f F" %}
This would display as "It is the 4th of September".
Note
The format passed can also be one of the predefined ones DATE_FORMAT, DATETIME_FORMAT, SHORT_DATE_FORMAT orSHORT_DATETIME_FORMAT. The predefined formats may vary depending on the current locale and if Format localizationis enabled, e.g.:
It is {% now "SHORT_DATETIME_FORMAT" %}
regroup
Regroups a list of alike objects by a common attribute.
This complex tag is best illustrated by use of an example: say that people is a list of people represented by dictionaries withfirst_name, last_name, and gender keys:
people = [ {‘first_name‘: ‘George‘, ‘last_name‘: ‘Bush‘, ‘gender‘: ‘Male‘}, {‘first_name‘: ‘Bill‘, ‘last_name‘: ‘Clinton‘, ‘gender‘: ‘Male‘}, {‘first_name‘: ‘Margaret‘, ‘last_name‘: ‘Thatcher‘, ‘gender‘: ‘Female‘}, {‘first_name‘: ‘Condoleezza‘, ‘last_name‘: ‘Rice‘, ‘gender‘: ‘Female‘}, {‘first_name‘: ‘Pat‘, ‘last_name‘: ‘Smith‘, ‘gender‘: ‘Unknown‘}, ]
...and you‘d like to display a hierarchical list that is ordered by gender, like this:
- Male:
- George Bush
- Bill Clinton
- Female:
- Margaret Thatcher
- Condoleezza Rice
- Unknown:
- Pat Smith
You can use the {% regroup %} tag to group the list of people by gender. The following snippet of template code would accomplish this:
{% regroup people by gender as gender_list %} <ul> {% for gender in gender_list %} <li>{{ gender.grouper }} <ul> {% for item in gender.list %} <li>{{ item.first_name }} {{ item.last_name }}</li> {% endfor %} </ul> </li> {% endfor %} </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 people list by the gender attribute and calling the resultgender_list.
{% regroup %} produces a list (in this case, gender_list) of group objects. Each group object has two attributes:
- grouper -- the item that was grouped by (e.g., the string "Male" or "Female").
- list -- a list of all items in this group (e.g., a list of all people with gender=‘Male‘).
Note that {% regroup %} does not order its input! Our example relies on the fact that the people list was ordered by gender in the first place. If the people list did not order its members by gender, the regrouping would naively display more than one group for a single gender. For example, say the people list was set to this (note that the males are not grouped together):
people = [ {‘first_name‘: ‘Bill‘, ‘last_name‘: ‘Clinton‘, ‘gender‘: ‘Male‘}, {‘first_name‘: ‘Pat‘, ‘last_name‘: ‘Smith‘, ‘gender‘: ‘Unknown‘}, {‘first_name‘: ‘Margaret‘, ‘last_name‘: ‘Thatcher‘, ‘gender‘: ‘Female‘}, {‘first_name‘: ‘George‘, ‘last_name‘: ‘Bush‘, ‘gender‘: ‘Male‘}, {‘first_name‘: ‘Condoleezza‘, ‘last_name‘: ‘Rice‘, ‘gender‘: ‘Female‘}, ]
With this input for people, the example {% regroup %} template code above would result in the following output:
- Male:
- Bill Clinton
- Unknown:
- Pat Smith
- Female:
- Margaret Thatcher
- Male:
- George Bush
- Female:
- Condoleezza Rice
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 people|dictsort:"gender" by gender as gender_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 "gender" field is a foreign key to a class with an attribute "description," you could use:
{% regroup people by gender.description as gender_list %}
Or, if gender is a field with choices, it will have a ^django.db.models.Model.get_FOO_display() method available as an attribute, allowing you to group on the display string rather than the choices key:
{% regroup people by get_gender_display as gender_list %}
{{ gender.grouper }} will now display the value fields from the choices set rather than the keys.
spaceless
Removes whitespace between HTML tags. This includes tab characters and newlines.
Example usage:
{% spaceless %} <p> <a href=http://www.mamicode.com/"foo/">Foo</a> </p> {% endspaceless %}
This example would return this HTML:
<p><a href=http://www.mamicode.com/"foo/">Foo</a></p>
Only space between tags is removed -- not space between tags and text. In this example, the space around Hello won‘t be stripped:
{% spaceless %} <strong> Hello </strong> {% endspaceless %}
ssi
Outputs the contents of a given file into the page.
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 %}
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 your Django settings, as a security measure.
See also: {% include %}.
Forwards compatibility
In Django 1.5, the behavior of the ssi template tag will change, with the first argument being made into a context variable, rather than being a special case unquoted constant. This will allow the ssi tag to use a context variable as the value of the page to be included.
In order to provide a forwards compatibility path, Django 1.3 provides a future compatibility library -- future -- that implements the new behavior. To use this library, add a load call at the top of any template using the ssitag, and wrap the first argument to the ssi tag in quotes. For example:
{% load ssi from future %} {% ssi ‘/home/html/ljworld.com/includes/right_generic.html‘ %}
In Django 1.5, the unquoted constant behavior will be replaced with the behavior provided by the future tag library. Existing templates should be migrated to use the new syntax.
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:
Argument Outputsopenblock | {% |
closeblock | %} |
openvariable | {{ |
closevariable | }} |
openbrace | { |
closebrace | } |
opencomment | {# |
closecomment | #} |
url
Returns an absolute path reference (a URL without the domain name) matching a given view function and optional parameters. This is a way to output links without violating the DRY principle by having to hard-code URLs in your templates:
{% url path.to.some_view v1 v2 %}
The first argument is a path to a view function in the format package.package.module.function. Additional arguments are optional and should be space-separated values that will be used as arguments in the URL. The example above shows passing positional arguments. Alternatively you may use keyword syntax:
{% url path.to.some_view 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:
(‘^client/(\d+)/$‘, ‘app_views.client‘)
If this app‘s URLconf is included into the project‘s URLconf under a path such as this:
(‘^clients/‘, include(‘project_name.app_name.urls‘))
...then, in a template, you can create a link to this view like this:
{% url app_views.client client.id %}
The template tag will output the string /clients/client/123/.
If you‘re using named URL patterns, you can refer to the name of the pattern in the url tag instead of using the path to the view.
Note that if the URL you‘re reversing doesn‘t exist, you‘ll get an ^django.core.urlresolvers.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:
{% url path.to.view arg arg2 as the_url %} <a href=http://www.mamicode.com/"{{ the_url }}">I‘m linking to {{ the_url }}</a>
This {% url ... as var %} syntax will not cause an error if the view is missing. In practice you‘ll use this to link to views that are optional:
{% url path.to.view as the_url %} {% if the_url %} <a href=http://www.mamicode.com/"{{ the_url }}">Link to optional stuff</a> {% endif %}
If you‘d like to retrieve a namespaced URL, specify the fully qualified name:
{% url myapp:view-name %}
This will follow the normal namespaced URL resolution strategy, including using any hints provided by the context as to the current application.
For backwards compatibility, the {% url %} tag also supports the use of commas to separate arguments. You shouldn‘t use this in any new projects, but for the sake of the people who are still using it, here‘s what it looks like:
{% url path.to.view arg,arg2 %} {% url path.to.view arg, arg2 %}
This syntax doesn‘t support the use of literal commas, or equals signs. Did we mention you shouldn‘t use this syntax in any new projects?
Forwards compatibility
In Django 1.5, the behavior of the url template tag will change, with the first argument being made into a context variable, rather than being a special case unquoted constant. This will allow the url tag to use a context variable as the value of the URL name to be reversed.
In order to provide a forwards compatibility path, Django 1.3 provides a future compatibility library -- future -- that implements the new behavior. To use this library, add a load call at the top of any template using the urltag, and wrap the first argument to the url tag in quotes. For example:
{% load url from future %} {% url ‘app_views.client‘ %} {% url ‘myapp:view-name‘ %} {% with view_path="app_views.client" %} {% url view_path client.id %} {% endwith %} {% with url_name="client-detail-view" %} {% url url_name client.id %} {% endwith %}
The new library also drops support for the comma syntax for separating arguments to the url template tag.
In Django 1.5, the old behavior will be replaced with the behavior provided by the future tag library. Existing templates be migrated to use the new syntax.
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=http://www.mamicode.com/"bar.gif" height="10" width="{% widthratio this_value max_value 100 %}" />
Above, if this_value is 175 and max_value is 200, 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).
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.
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.
You can assign more than one context variable:
{% with alpha=1 beta=2 %} ... {% endwith %}
Note
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.
For example:
{{ 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:
{{ 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].
Warning
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.
For example:
{{ 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.
For example:
{{ value|capfirst }}
If value is "django", the output will be "Django".
center
Centers the value in a field of a given width.
For example:
"{{ value|center:"15" }}"
If value is "Django", the output will be " Django ".
cut
Removes all values of arg from the given string.
For example:
{{ 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 (http://php.net/date) with some differences.
Available format strings:
Format character Description Example outputa | ‘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 | Not implemented. | |
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. | 0 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 |
The c and u format specification characters were added in Django 1.2.
The e and o format specification characters were added in Django 1.4.
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.
default
If value evaluates to False, uses the given default. Otherwise, uses the value.
For example:
{{ 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.
For example:
{{ value|default_if_none:"nothing" }}
If value is None, the output will be the string "nothing".
dictsort
Takes a list of dictionaries and returns that list sorted by the key given in the argument.
For example:
{{ value|dictsort:"name" }}
If value is:
[ {‘name‘: ‘zed‘, ‘age‘: 19}, {‘name‘: ‘amy‘, ‘age‘: 22}, {‘name‘: ‘joe‘, ‘age‘: 31}, ]
then the output would be:
[ {‘name‘: ‘amy‘, ‘age‘: 22}, {‘name‘: ‘joe‘, ‘age‘: 31}, {‘name‘: ‘zed‘, ‘age‘: 19}, ]
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.
For example:
{{ value|divisibleby:"3" }}
If value is 21, the output would be True.
escape
Escapes a string‘s HTML. Specifically, it makes these replacements:
- < is converted to <
- > is converted to >
- ‘ (single quote) is converted to '
- " (double quote) is converted to "
- & is converted to &
The escaping is only applied when the string is output, so it does not matter where in a chained sequence of filters you putescape: it will always be applied as though it were the last filter. If you want escaping to be applied immediately, use theforce_escape filter.
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.
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
Formats the value like a ‘human-readable‘ file size (i.e. ‘13 KB‘, ‘4.1 MB‘, ‘102 bytes‘, etc).
For example:
{{ value|filesizeformat }}
If value is 123456789, the output would be 117.7 MB.
first
Returns the first item in a list.
For example:
{{ value|first }}
If value is the list [‘a‘, ‘b‘, ‘c‘], the output will be ‘a‘.
fix_ampersands
Note
This is rarely useful as ampersands are automatically escaped. See escape for more information.
Replaces ampersands with & entities.
For example:
{{ value|fix_ampersands }}
If value is Tom & Jerry, the output will be Tom & Jerry.
However, ampersands used in named entities and numeric character references will not be replaced. For example, if value isCafé, the output will not be Caf&eacute; but remain Café. This means that in some edge cases, such as acronyms followed by semicolons, this filter will not replace ampersands that need replacing. For example, if value isContact the R&D;, the output will remain unchanged because &D; resembles a named entity.
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 Output34.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 Output34.23234 | {{ value|floatformat:3 }} | 34.232 |
34.00000 | {{ value|floatformat:3 }} | 34.000 |
34.26000 | {{ value|floatformat:3 }} | 34.260 |
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 Output34.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.
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&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‘], the output will be 4.
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‘], 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\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 />).
For example:
{{ value|linebreaksbr }}
If value is Joel\nis 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 [u‘J‘, u‘o‘, u‘e‘, u‘l‘]. If value is 123, the output will be the list[u‘1‘, u‘2‘, u‘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
Returns a plural suffix if the value is not 1. By default, this suffix is ‘s‘.
Example:
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.
Example:
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.
Example:
You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.
Note
Use blocktrans to pluralize translated strings.
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
Removes a space-separated list of [X]HTML tags from the output.
For example:
{{ value|removetags:"b span"|safe }}
If value is "<b>Joel</b> <button>is</button> a <span>slug</span>" the 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 output will be "<B>Joel</B> <button>is</button> a slug".
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. Seehttp://diveintopython.net/native_data_types/lists.html#odbchelper.list.slice for an introduction.
Example:
{{ some_list|slice:":2" }}
If some_list is [‘a‘, ‘b‘, ‘c‘], the output will be [‘a‘, ‘b‘].
slugify
Converts to lowercase, removes non-word characters (alphanumerics and underscores) and converts spaces to hyphens. 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 http://docs.python.org/library/stdtypes.html#string-formatting-operations for documentation of Python string formatting
For example:
{{ value|stringformat:"s" }}
If value is "Joel is a slug", the output will be "Joel is a slug".
striptags
Strips 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".
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-dependant.
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, use the date filter.
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").
When used without a format string:
{{ value|time }}
...the formatting string defined in the TIME_FORMAT setting will be used, without applying any localization.
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_dateis a date instance for 08:00 on 1 June 2006, then {{ blog_date|timesince:comment_date }} would return "8 hours".
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). Iffrom_date contains 22 June 2006, then {{ conference_date|timeuntil:from_date }} will return "1 week".
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.
For example:
{{ 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 sequence ("...").
Argument: Number of characters to truncate to
For example:
{{ value|truncatechars:9 }}
If value is "Joel is a slug", the output will be "Joel i...".
truncatewords
Truncates a string after a certain number of words.
Argument: Number of words to truncate after
For example:
{{ 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.
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
Recursively takes a self-nested list and returns an HTML unordered list -- WITHOUT opening and closing <ul> 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:
<li>States <ul> <li>Kansas <ul> <li>Lawrence</li> <li>Topeka</li> </ul> </li> <li>Illinois</li> </ul> </li>
Note: An older, more restrictive and verbose input format is also supported:[‘States‘, [[‘Kansas‘, [[‘Lawrence‘, []], [‘Topeka‘, []]]], [‘Illinois‘, []]]],
upper
Converts a string into all uppercase.
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".
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:
{{ value|urlencode:"" }}
If value is "http://www.example.org/", the output will be "http%3A%2F%2Fwww.example.org%2F".
urlize
Converts URLs in text into clickable links.
This template tag works on links prefixed with http://, https://, or www.. For example, http://goo.gl/aia1t will get converted butgoo.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.
Until Django 1.4, only the .com, .net and .org suffixes were supported for domain-only links.
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.
For example:
{{ value|urlize }}
If value is "Check out www.djangoproject.com", the output will be"Check out <a href=http://www.mamicode.com/"http://www.djangoproject.com" rel="nofollow">www.djangoproject.com".
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 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.mamicode.com/"http://www.djangoproject.com" rel="nofollow">www.djangopr...‘.
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 }}
If value is Joel is a slug, the output would be:
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:
For example:
{{ value|yesno:"yeah,no,maybe" }}
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 Internationalization: in template code.
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 Controlling localization in templates.
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 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.markup
A collection of template filters that implement these common markup languages:
- Textile
- Markdown
- reST (reStructuredText)
See the markup documentation.
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. Seedjango.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=http://www.mamicode.com/"{% static "images/hi.jpg" %}" />
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=http://www.mamicode.com/"{% static user_stylesheet %}" type="text/css" media="screen" />
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. 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=http://www.mamicode.com/"{% static "images/hi.jpg" %}" />
get_static_prefix
If you‘re not using RequestContext, or 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 instead:
{% load static %} <img src=http://www.mamicode.com/"{% get_static_prefix %}images/hi.jpg" />
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=http://www.mamicode.com/"{{ STATIC_PREFIX }}images/hi.jpg" /> <img src=http://www.mamicode.com/"{{ STATIC_PREFIX }}images/hi2.jpg" />
get_media_prefix
Similar to the get_static_prefix, get_media_prefix populates a template variable with the media prefix MEDIA_URL, e.g.:
<script type="text/javascript" charset="utf-8"> var media_path = ‘{% get_media_prefix %}‘; </script>