Built-in Django tags
Django offers several built-in tags that offer immediate access to elaborate operations on Django templates. Unlike Django filters which operate on individual variables, tags are designed to produce results without a variable or operate across template sections.
I’ll classify each of these built-in tags into functional sections so it’s easier to identify them. The functional classes I’ll use are: Dates, forms, comparison operations, loops, Python & filter operations, spacing and special characters, template structures, development and testing & urls.
Dates
<% now %>.- The <% now %>tag offers access to the current system time. The <% now %>tag accepts a second argument to format the system date. For example, if the system date is 01/01/2022 for the statement <% now "F jS o" %>the tag output is January 1st 2022. The string syntax for the <% now %>tag is based on Django date characters described in table 3-3. It’s also possible to use the as keyword to re-use the value through a variable(e.g. <% now "Y" as current_year %>and later in the template declare Copyright <
Forms
<% csrf_token %>.- The <% csrf_token %>tag provides a string to prevent cross site scripting. The <% csrf_token %>tag is only intended to be used inside HTML <form> tags. The data output of the <% csrf_token %>tag allows Django to prevent request forgeries (e.g. HTTP POST requests) from form data submissions. More details about the <% csrf_token %>tag are provided in the Django forms chapter.
Comparison operations
<% if %>with <% elif %> <% else %>.- The <% if %>tag is typically used in conjunction with the <% elif %>and <% else %>tags to evaluate more than one condition. An <% if %>tag with an argument variable evaluates to true if a variable exists and is not empty or if the variable holds a True boolean value. Listing 3-18 illustrates a series of <% if %>tag examples.
Listing 3-18. Django <% if %>tag with <% elif %>and
<% if %>with and , or and not operators.- The <% if %>tag also supports the and , or and not operators to create more elaborate conditions. These operators allow you to compare if more than one variable is not empty (e.g. <% if drinks and drinks_on_sale %>), if one or another variable is not empty (e.g. <% if drinks or drinks_on_sale %>) or if a variable is empty (e.g. <% if not drinks %>).
<% if %>with == , != , < , > , <= and >= operators.- The <% if %>tag also supports equal, not equal, larger than and less than operators to create conditions that compare variables to fixed strings or numbers. These operators allow you to compare if a variable equals a string or number (e.g. <% if drink == "mocha" %>), if a variable does not equal a variable or number (e.g. <% if store.id != 2 %>) or if a variable is greater than or lesser than a number (e.g. <% if store.id > 5 %>).
<% firstof %>.- The <% firstof %>tag is a shorthand tag to output the first variable in a set of variables that’s not empty. The same functionality of the <% firstof %>tag is achieved by nesting <% if %>tags. Listing 3-19 illustrates a sample of the < % firstof %>tag, as well as an equivalent set of nested <% if %>tags.
Listing 3-19. Django <% firstof %>tag and equivalent <% if %><% elif %> <% else %>tags
<% if <value> in %>and <% if <value> not in %>.- The <% if %>tag also supports the in and not in operators to verify the presence of a constant or variable. For example <% if "mocha" in drinks %>tests if the value «mocha» is in the drinks list variable or <% if 2 not in stores %>tests if the value 2 is not in the stores list variable. Although the in and not in operators are commonly used to test list variables, it’s also possible to test the presence of characters on strings (e.g. <% if "m" in drink %>). In addition, it’s also possible to compare if the value of one variable is present in another variable (e.g. <% if order_drink in drinks %>).
<% if <value> is <value> %>and <% if <value> is not %>.- The <% if %>tag also supports the is and is not operators to make object-level comparisons. For example <% if target_drink is None %>tests if the value target_drink is a None object or <% if daily_special is not True %>tests if the value daily_special is not True .
<% if value|<filter> <condition> <value> %>.- The <% if %>tag also supports applying filters directly on a value and then performing an evaluation. For example, <% if target_drink_list|random == user_drink %>Congratulations your drink just got selected! <% endif %>uses the random filter directly in a condition.
Comparison operators are often aggregated into single statements (e.g. if. <. or. >. and. ==. ) and follow a certain execution precedence. Django follows the same operator precedence as Python [5] . So for example, the statement <% if drink in specials or drink == drink_of_the_day %>gets evaluated as ((drink in specials) or (drink == drink_of_the_day)) , where the internal parenthesis operations are run first, since in and == have higher precedence than or.
In Python you can alter this precedence by using explicit parenthesis in comparison statements. However, Django does not support the use of parenthesis in <% if %>tags, you must either rely on operator precedence or use nested <% if %>statements to declare the same logic produced by explicit parenthesis.
Loops
<% for %>and <% for %>with <% empty %>.- The <% for %>tag iterates over items on a dictionary, list, tuple or string variable. The <% for %>tag syntax is <% for <reference> in <variable> %>, where reference is assigned a new value from variable on each iteration.
Depending on the nature of a variable there can be one or more references (e.g. for a list one reference <% for item in list %>, for a dictionary two references <% for key,value in dict.items %>).In addition, it’s also possible to invert the loop sequence with the reversed keyword (e.g. < % for item in list reversed %>).The <% for %>tag also supports the <% empty %>tag which is processed in case there are no iterations in a loop (i.e. the main variable is empty). Listing 3-20 illustrates a <% for %>and a <% for %>and <% empty %>loop example.
Listing 3-20 Django <% for %>tag and <% for %>with
The <% for %>tag also generates a series of variables to manage the iteration process, such as an iteration counter, a first iteration flag and a last iteration flag. These variables can be useful when you want to create behaviors (e.g. formatting, additional processing) on a given iteration. Table 3-4 illustrates the <% for %>tag variables.
Table 3-4 Django <% for %>tag variables
The current iteration of the loop (1-indexed)
The current iteration of the loop (0-indexed)
The number of iterations from the end of the loop (1-indexed)
The number of iterations from the end of the loop (0-indexed)
True if it’s the first time through the loop
True if it’s the last time through the loop
For nested loops, this is the parent loop to the current one
<% ifchanged %>.- The <% ifchanged %>tag is a special logical tag used inside <% for %>tags. Sometimes it’s helpful to know if a loop reference has changed from one iteration to the other (e.g. to insert a new title). The argument for the <% ifchanged %>tag is the loop reference itself (e.g. <% ifchanged drink %><
<% cycle %>.- The <% cycle %>tag is used inside <% for %>tags to iterate over a given set of strings or variables. One of the primary uses of the <% cycle %>tag is to define CSS classes so each iteration receives a different CSS class. For example, if you want assign different CSS classes to a list so each line appears in different colors (e.g. white, grey, white, grey) you can use <li > , in this manner on each loop iteration the class value alternates between white and grey. The <% cycle %>tag can iterate sequentially over any number of strings or variables (e.g. <% cycle var1 var2 'red' %>).
By default, a <% cycle %>tag progresses through its values on the basis of its enclosing loop (i.e. one by one). But under certain circumstances, you may need to use a <% cycle %>tag outside of a loop or explicitly declare how a <% cycle % >tag advances. You can achieve this behavior by naming the <% cycle %>tag with the as keyword, as illustrated in listing 3-21.
Listing 3-21 Django <% cycle %>with explicit control of progression
As you can see in listing 3-21, the <% cycle %>tag statement initially produces the first value and afterwards you can continue using the cycle reference name to output the same value. In order to advance to the next value in the cycle, you call the <% cycle %>once more with the cycle reference name. A minor side-effect of the <% cycle %>tag is that it outputs its initial value where it’s declared, something that can be problematic if you plan to use the cycle as a placeholder or in nested loops. To circumvent this side-effect, you can use the silent keyword after the cycle reference name (e.g. < % cycle 'disc' 'circle' 'square' as bullettype silent %>).
<% resetcycle %>.- The <% resetcycle %>tag is used is to re-initiate a <% cycle %>tag to its first element. A <% cycle %>tag always loops over its entire set of values before returning to its first one, something that can be problematic in the context of nested loops. For example, if you want to assign three color codes (e.g. <% cycle 'red' 'orange' 'yellow' %>) to nested groups, the first group can consist of two elements that use up the first two cycle values (e.g. ‘red’ ‘orange’), which means the second group starts on the third color code (e.g.’yellow’). In order for the second group to start with the first <% cycle %>element again, you can use the <% resetcycle %>tag after a nested loop iteration finishes so the <% cycle %>tag returns to its first element.
<% regroup %>.- The <% regroup %>tag is used to rearrange the contents of a dictionary variable into different groups. The <% regroup %>tag avoids the need to create complex conditions inside a <% for %>tag to achieve the desired display. The <% regroup %>tag arranges the contents of a dictionary beforehand, making the <% for %>tag logic simpler. Listing 3-22 illustrates a dictionary with the use of the <% regroup %>tag along with its output.
Listing 3-22 Django <% for %>tag and
Python & filter operations
<% filter %>.- The <% filter %>tag is used to apply Django filters to template sections. If you declare <% filter lower %>the lower filter is applied to all variables between this tag and the <% endfilter %>tag — note the filter lower converts all content to lowercase. It’s also possible to apply multiple filters to the same section using the same pipe technique to chain filters to variables (e.g. <% filter lower|center:"50" %>. variables to convert to lower case and center. <% endfilter %>).
<% with %>.- The <% with %>tag lets you define variables in the context of Django templates. It’s useful when you need to create variables for values that aren’t exposed by a Django view method or when a variable is tied to a heavyweight operation. It’s also possible to define multiple variables in the same <% with %>tag (e.g. <% with drinkwithtax=drink.cost*1.07 drinkpromo=drink.cost*0.85 %>). Each variable defined in a <% with %>tag is made available to the template until the <% endwith %>tag is reached.
Django templates don’t allow the inclusion of inline Python logic. In fact, the closest thing Django templates allow to inline Python logic is through the <% with %>tag which isn’t very sophisticated.
The only way to make custom Python logic work in Django templates is to embed the code inside a custom Django tag or filter. This way you can place a custom Django tag or filter on a template and the Python logic runs behind the scenes. The next section describes how to create custom Django filters.
Spacing and special characters
<% autoescape %>.- The <% autoescape %>tag is used to escape HTML characters from a template section. The <% autoescape %>accepts one of two arguments on or off . With <% autoescape on %>all template content between this tag and the <% endautoescape %>tag is HTML escaped & with <% autoescape off %>all template content between this tag and the <% endautoescape %>tag is not escaped.
<% spaceless %>.- The <% spaceless %>tag removes whitespace between HTML tags, including tab characters and newlines. Therefore all HTML content contained within the <% spaceless %>and <% endspaceless %>becomes more compact. Note the <% spaceless %>tag only removes space between HTML tags, it does not remove space between text and HTML tags (e.g. <p> <span> my span </span> </p> , only the space between <p> <span> and </span> </p> tags is removed, the space between <span> tags that pads the myspan string remains).
<% templatetag %>.- The <% templatetag %>tag is used to output reserved Django template characters. So if by any chance you want to display any of the characters <% , %>, << , >> , < , >, <# or #>verbatim on a template you can. The <% templatetag %>is used in conjunction with one of eight arguments to represent Django template characters. <% templatetag openblock %>outputs <% , <% templatetag closeblock %>outputs %> , <% templatetag openvariable %>outputs << , <% templatetag closevariable %>outputs >> , <% templatetag openbrace %>outputs < , <% templatetag closebrace %>outputs > , <% templatetag opencomment %>outputs <# and <% templatetag closecomment %>outputs #> . A simpler approach is to wrap reserved Django characters with the <% verabtim %>tag.
<% verbatim %>.- The <% verbatim %>tag is used to isolate template content from being processed. Any content inside the <% verbatim %>tag and <% endverbatim %>tag is bypassed by Django. This means special characters like << , variable statements like <
<% widthratio %>.- The <% widthratio %>tag is used to calculate the ratio of a value to a maximum value. The <% widthratio %>tag is helpful for displaying content that is fixed in width but requires to be scaled based on the amount of available space, such as the case with images and charts. For example, given the statement <img src=»logo.gif» style=»width:<% widthratio available_width image_width 100 %>%»/> , if the available_width is 75 and image_width is 150 it results in 0.50 multiplied by 100 which results in 50. This image’s width ratio is calculated based on the available space and image size, in this case the statement is rendered as: <img src=»logo.gif» style=»width:50%»/> .
<% lorem %>.- The <% lorem %>tag is used to display random latin text, which is useful for filler on templates. The <% lorem %>tag supports up to three parameters <% lorem [count] [method] [random] %>. Where [count] is a number or variable with the number of paragraphs or words to generate, if not provided the default [count] is 1. Where [method] is either w for words, p for HTML paragraphs or b for plain-text paragraph blocks, if not provided the default [method] is b . And where the word random (if given) outputs random Latin words, instead of a common pattern (e.g. Lorem ipsum dolor sit amet. ).
Template structures
<% block %>.- The <% block %>tag is used to define page sections that can be overridden on different Django templates. See the previous section in this chapter on how to create reusable templates for examples of this tag.
<% comment "Optional explanation" %>.- The <% comment %>tag is used to define comment sections on Django templates. Any content placed between the <% comment %>and <% endcomment %>tag is bypassed by Django and doesn’t appear in the final rendered web page. Note the string argument in the opening <% comment %>tag is optional, but helps clear up the purpose of the comment.
<# #>.- The <#>syntax can be used for a single line comment on Django templates. Any content placed between <# and #>in a single line is bypassed by Django and doesn’t appear in the final rendered web page. Note that if the comment spans multiple lines you should use the <% comment %>tag.
<% extends %>.- The <% extends %>tag is used to reuse the layout of another Django template. See the previous section in this chapter on creating reusable templates for examples of this tag.
<% include %>.- The <% include %>tag is used to embed a Django template on another Django template. See the previous section in this chapter on creating reusable templates for examples of this tag.
<% load %>.- The <% load %>tag is used to load custom Django tags and filters. The <% load %>tag requires one or multiple arguments to be the names of the custom Django tags or filters. The next section of this chapter describes how to create custom filters and how to use the <% load %>tag.
Development and testing
<% debug %>.- The <% debug %>tag outputs debugging information that includes template variables and imported modules. The <% debug %>tag is useful during development and testing because it outputs ‘behind the scenes’ information used by Django templates.
Autoescape django что это
Django предоставляет возможность использовать в шаблонах ряд специальных тегов, которые упрощают вывод некоторых данных. Рассмотрим некоторые наиболее используемые теги.
autoescape
Тег autoescape позволяет автоматически экранировать ряд символов HTML и тем самым сделать вывод на страницу более безопасным. В частности, производятся следующие замены:
< заменяется на <
> заменяется на >
‘ (одинарная кавычка) заменяется на '
» (двойная кавычка) заменяется на "
Например, пусть у нас будет определен следующий шаблон index.html :
Здесь в шаблоне два раза выводится содержимое переменной body . Однако сначала она выводится сама по себе, в во втором случае ее вывод помещается в между тегами <% autoescape %>и <% endautoescape %>. Тег в качестве параметра принимает одно из значений: on (экранирование включено) и off (экранирование отключено). В данном случае тегу передается значение off , а это значит, что внутри блока тега autoescape экранирование отключено.
Определим следующую функцию-представление, которая использует данный шаблон и передает в него некоторые данные:
Здесь в шаблон передается некоторая строка с кодом HTML. По умолчанию шаблоны применяют экранирование. Поэтому на веб-странице мы увидим код html в текстовом виде, а во втором случае переданные данные будут интпретированы непосредственно как код html:

Комментарии
Для определения комментариев в шаблоне применяется тег comment : все, что помещается между тегами <% comment %>и <% endcomment %>, игнорируется при генерации html-страницы.
if..else
Тег if оформляется в виде блока:
Этот тег оценивает некоторое условие, которое должно возращать True или False : если возвращается True , то выводится содержимое блока <% if %>.
Например, пусть в представлении передаются в шаблон некоторые значения:
В шаблоне в зависимости от значения переменной n мы можем выводить определенный контент:
То есть если n больше 0, то будет выводиться, что число положительное. Если n меньше или равно 0, ничего не будет выводиться.
С помощью дополнительного тега <% else %>можно вывести контент в случае, если условие после if равно False:
С помощью тега <% elif %>можно проверить дополнительные условия, если условие в if равно False:
Стоит отметить, что в условии, которое передается тегу if , можно применять ряд операторов, которые возвращают True или False: == , != , < , > , <= , >= , in , not in , is , is not , and , or , not .
Циклы
Тег for позволяет создавать циклы. Этот тег принимает в качестве параметра некоторую коллекцию и пробегается по этой коллекции, обрабатывая каждый ее элемент.
Например, пусть из представления в шаблон передается некоторый список:
Выведем элементы списка langs в шаблоне с помощью тега for :

Вполне возможно, что переданная из представления в шаблон коллекция окажется пустой. На этот случай мы можем использовать тег <% empty %>:
Подобным образом можно перебирать в шаблоне другие коллекции, например, словари:
В данном случае перебирается словарь data, который передается из представления:
Определение переменных
Тег <% with %>позволяет определить переменную и использовать ее внутри блока тега. Например:
В данном случае определены две переменных: name и age, которые мы можем использовать внутри блока <% with%>. <% endwith %>. Однако вне этого блока эти переменные использоваться не могут.
Тег <% now "формат_данных" %>позволяет вывести системное время. В качестве параметра тегу now передается формат данный, который указывает, как форматировать время и дату.

Символ «Y» передает год в виде четырех цифр, «y» — берет из года последние две цифры. «F» — полное название месяца, «N» -сокращенное название месяца. «j» — день месяца. «P» — время. Все возможные форматы для вывода даты и времени можно посмотреть в документации
Стоит отметить, что в качестве времени Django берет значение переменной из файла settinds.py , которая по умолчанию имеет следующее определение:
То есть отсчитывается относительно UTC. Это может быть не всегда удобно. И соответственно мы можем изменить ее значение на нужное. Например, настройка для московского часового пояса:
Built-in template tags and filters¶
This document describes Django’s built-in template tags and filters. It is recommended that you use the automatic documentation , if available, as this will also include documentation for any custom tags or filters installed.
Built-in tag reference¶
autoescape ¶
Controls the current auto-escaping behavior. This tag takes either on or off as an argument and that determines whether auto-escaping is in effect inside the block. The block is closed with an endautoescape ending tag.
When auto-escaping is in effect, all content derived from variables has HTML escaping applied before placing the result into the output (but after any filters are applied). This is equivalent to manually applying the escape filter to each variable.
The only exceptions are variables already marked as “safe” from escaping. Variables could be marked as “safe” by the code which populated the variable, by applying the safe or escape filters, or because it’s the result of a previous filter that marked the string as “safe”.
Within the scope of disabled auto-escaping, chaining filters, including escape , may cause unexpected (but documented) results such as the following:
The above code will output the joined elements of my_list unescaped. This is because the filter chaining sequence executes first join on my_list (without applying escaping to each item since autoescape is off ), marking the result as safe. Subsequently, this safe result will be fed to escape filter, which does not apply a second round of escaping.
block ¶
Defines a block that can be overridden by child templates. See Template inheritance for more information.
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.
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:
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:
Variables included in the cycle will be escaped. You can disable auto-escaping with:
You can mix variables and strings:
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:
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:
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:
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 :
You can use the resetcycle tag to make a <% cycle %>tag restart from its first value when it’s next encountered.
debug ¶
Outputs a whole load of debugging information, including the current context and imported modules. <% debug %>outputs nothing when the DEBUG setting is False .
In older versions, debugging information was displayed when the DEBUG setting was False .
extends ¶
Signals that this template extends a parent template.
This tag can be used in two ways:
- <% extends "base.html" %>(with quotes) uses the literal value "base.html" as the name of the parent template to extend.
- <% extends variable %>uses the value of variable . If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.
See Template inheritance for more information.
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:
In template.html , the following paths would be valid:
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.
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”.
This is equivalent to:
You can also use a literal string as a fallback value in case all passed variables are False:
This tag auto-escapes variable values. You can disable auto-escaping with:
Or if only some variables should be escaped, you can use:
You can use the syntax <% firstof var1 var2 var3 as value %>to store the output inside a variable.
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 :
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:
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:
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 .
The for loop sets a number of variables available within the loop:
| Variable | Description |
|---|---|
| forloop.counter | The current iteration of the loop (1-indexed) |
| forloop.counter0 | The current iteration of the loop (0-indexed) |
| forloop.revcounter | The number of iterations from the end of the loop (1-indexed) |
| forloop.revcounter0 | The number of iterations from the end of the loop (0-indexed) |
| forloop.first | True if this is the first time through the loop |
| forloop.last | True if this is the last time through the loop |
| forloop.parentloop | For nested loops, this is the loop surrounding the current one |
for … empty ¶
The for tag can take an optional <% empty %>clause whose text is displayed if the given array is empty or could not be found:
The above is equivalent to – but shorter, cleaner, and possibly faster than – the following:
The <% if %>tag evaluates a variable, and if that variable is “true” (i.e. exists, is not empty, and is not a false boolean value) the contents of the block are output:
In the above, if athlete_list is not empty, the number of athletes will be displayed by the << athlete_list|length >> variable.
As you can see, the if tag may take one or several <% elif %>clauses, as well as an <% else %>clause that will be displayed if all previous conditions fail. These clauses are optional.
Boolean operators¶
if tags may use and , or or not to test a number of variables or to negate a given variable:
Use of both and and or clauses within the same tag is allowed, with and having higher precedence than or e.g.:
will be interpreted like:
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¶
!= operator¶
< operator¶
Less than. Example:
> operator¶
Greater than. Example:
<= operator¶
Less than or equal to. Example:
>= operator¶
Greater than or equal to. Example:
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:
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:
is not operator¶
Negated object identity. Tests if two values are not the same object. This is the negation of the is operator. Example:
Filters¶
You can also use filters in the if expression. For example:
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:
…will be interpreted as:
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:
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.
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:
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:
The ifchanged tag can also take an optional <% else %>clause that will be displayed if the value has not changed:
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" :
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 :
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" .
The name_snippet.html template:
You can pass additional context to the template using keyword arguments:
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:
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.
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 :
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 :
lorem ¶
Displays random “lorem ipsum” Latin text. This is useful for providing sample data in templates.
The <% lorem %>tag can be used with zero, one, two or three arguments. The arguments are:
| Argument | Description |
|---|---|
| count | A number (or variable) containing the number of paragraphs or words to generate (default is 1). |
| method | Either w for words, p for HTML paragraphs or b for plain-text paragraph blocks (default is b ). |
| random | The word random , which if given, does not use the common paragraph (“Lorem ipsum dolor sit amet…”) when generating text. |
- <% lorem %>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.
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.
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:
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 Format localization is enabled, e.g.:
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:
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:
…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
- New York: 20,000,000
- Chicago: 7,000,000
- 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:
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:
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):
With this input for cities , the example <% regroup %>template code above would result in the following output:
- India
- Mumbai: 19,000,000
- New York: 20,000,000
- Calcutta: 15,000,000
- Chicago: 7,000,000
- 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:
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:
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:
<< 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.
This example would return this HTML:
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:
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.
This example would return this HTML:
Only space between tags is removed – not space between tags and text. In this example, the space around Hello won’t be stripped:
templatetag ¶
Outputs one of the syntax characters used to compose template tags.
The template system has no concept of “escaping” individual characters. However, you can use the <% templatetag %>tag to display one of the template tag character combinations.
The argument tells which template bit to output:
Argument Outputs openblock <% closeblock %> openvariable << closevariable >> openbrace < closebrace > opencomment <# closecomment #> See also the verbatim tag for another way of including these characters.
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:
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:
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:
If this app’s URLconf is included into the project’s URLconf under a path such as this:
…then, in a template, you can create a link to this view like this:
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:
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:
If you’d like to retrieve a namespaced URL, specify the fully qualified 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:
You can also designate a specific closing tag, allowing the use of <% endverbatim %>as part of the unrendered contents:
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.
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:
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.
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:
The previous more verbose format is still supported:
Built-in filter reference¶
Adds the argument to the value.
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:
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.
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.
If value is "django" , the output will be "Django" .
center ¶
Centers the value in a field of a given width.
Removes all values of arg from the given string.
If value is "String with spaces" , the output will be "Stringwithspaces" .
Formats a date according to the given format.
Uses a similar format to PHP’s date() function 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 Description Example output Day d Day of the month, 2 digits with leading zeros. ’01’ to ’31’ j Day of the month without leading zeros. ‘1’ to ’31’ D Day of the week, textual, 3 letters. ‘Fri’ l Day of the week, textual, long. ‘Friday’ S English ordinal suffix for day of the month, 2 characters. ‘st’ , ‘nd’ , ‘rd’ or ‘th’ w Day of the week, digits without leading zeros. ‘0’ (Sunday) to ‘6’ (Saturday) z Day of the year. 1 to 366 Week W ISO-8601 week number of year, with weeks starting on Monday. 1 , 53 Month m Month, 2 digits with leading zeros. ’01’ to ’12’ n Month without leading zeros. ‘1’ to ’12’ M Month, textual, 3 letters. ‘Jan’ b Month, textual, 3 letters, lowercase. ‘jan’ E Month, locale specific alternative representation usually used for long date representation. ‘listopada’ (for Polish locale, as opposed to ‘Listopad’ ) F Month, textual, long. ‘January’ N Month abbreviation in Associated Press style. Proprietary extension. ‘Jan.’ , ‘Feb.’ , ‘March’ , ‘May’ t Number of days in the given month. 28 to 31 Year y Year, 2 digits with leading zeros. ’00’ to ’99’ Y Year, 4 digits with leading zeros. ‘0001’ , …, ‘1999’ , …, ‘9999’ L Boolean for whether it’s a leap year. True or False o ISO-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 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’ s Seconds, 2 digits with leading zeros. ’00’ to ’59’ u Microseconds. 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’ f Time, in 12-hour hours and minutes, with minutes left off if they’re zero. Proprietary extension. ‘1’ , ‘1:30’ 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.’ Timezone e Timezone name. Could be in any format, or might return an empty string, depending on the datetime. » , ‘GMT’ , ‘-500’ , ‘US/Eastern’ , etc. I Daylight saving time, whether it’s in effect or not. ‘1’ or ‘0’ O Difference to Greenwich time in hours. ‘+0200’ T Time zone of this machine. ‘EST’ , ‘MDT’ 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 Date/Time c ISO 8601 format. (Note: unlike other 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 r RFC 5322 formatted date. ‘Thu, 21 Dec 2000 16:01:07 +0200’ U Seconds since the Unix Epoch (January 1 1970 00:00:00 UTC). 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:
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:
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.:
default ¶
If value evaluates to False , uses the given default. Otherwise, uses the value.
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.
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.
autoescape Template Tag
The autoescape tag is used to specify if autoescape is on or off.
If autoescape is on, which is default, HTML code in variables will be escaped.
When escape is on, these characters are escaped:
- < is converted to <
- > is converted to >
- ‘ is converted to '
- » is converted to "
- & is converted to &
Example
With autoescape on, any HTML elements inside variables will be converted according to the list above.
Syntax
Parameters
Value Description on Default. Specifies that the block will be escaped off Specifies that the block will not be escaped 
COLOR PICKER


Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Thank You For Helping Us!
Your message has been sent to W3Schools.
Top Tutorials
Top References
Top Examples
Get Certified
W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.