Variable | GroupedResult |
Undocumented |
Variable | register |
Undocumented |
Class | AutoEscapeControlNode |
Implement the actions of the autoescape tag. |
Class | CommentNode |
Undocumented |
Class | CsrfTokenNode |
Undocumented |
Class | CycleNode |
No class docstring; 0/3 instance variable, 1/3 method documented |
Class | DebugNode |
Undocumented |
Class | FilterNode |
Undocumented |
Class | FirstOfNode |
Undocumented |
Class | ForNode |
Undocumented |
Class | IfChangedNode |
Undocumented |
Class | IfNode |
Undocumented |
Class | LoadNode |
Undocumented |
Class | LoremNode |
Undocumented |
Class | NowNode |
Undocumented |
Class | RegroupNode |
Undocumented |
Class | ResetCycleNode |
Undocumented |
Class | SpacelessNode |
Undocumented |
Class | TemplateIfParser |
Undocumented |
Class | TemplateLiteral |
Undocumented |
Class | TemplateTagNode |
Undocumented |
Class | URLNode |
Undocumented |
Class | VerbatimNode |
Undocumented |
Class | WidthRatioNode |
Undocumented |
Class | WithNode |
Undocumented |
Function | autoescape |
Force autoescape behavior for this block. |
Function | comment |
Ignore everything between {% comment %} and {% endcomment %}. |
Function | csrf_token |
Undocumented |
Function | cycle |
Cycle among the given strings each time this tag is encountered. |
Function | debug |
Output a whole load of debugging information, including the current context and imported modules. |
Function | do_filter |
Filter the contents of the block through variable filters. |
Function | do_for |
Loop over each item in an array. |
Function | do_if |
Evaluate a variable, and if that variable is "true" (i.e., exists, is not empty, and is not a false boolean value), output the contents of the block: |
Function | do_with |
Add one or more values to the context (inside of this block) for caching and easy access. |
Function | find_library |
Undocumented |
Function | firstof |
Output the first variable passed that is not False. |
Function | ifchanged |
Check if a value has changed from the last iteration of a loop. |
Function | load |
Load a custom template tag library into the parser. |
Function | load_from_library |
Return a subset of tags and filters from a library. |
Function | lorem |
Create random Latin text useful for providing test data in templates. |
Function | now |
Display the date, formatted according to the given string. |
Function | regroup |
Regroup a list of alike objects by a common attribute. |
Function | resetcycle |
Reset a cycle tag. |
Function | spaceless |
Remove whitespace between HTML tags, including tab and newline characters. |
Function | templatetag |
Output one of the bits used to compose template tags. |
Function | url |
Return an absolute URL matching the given view with its parameters. |
Function | verbatim |
Stop the template engine from rendering the contents of this block tag. |
Function | widthratio |
For creating bar charts and such. Calculate the ratio of a given value to a maximum value, and then apply that ratio to a constant. |
Cycle among the given strings each time this tag is encountered.
Within a loop, cycles among the given strings each time through the loop:
{% for o in some_list %} <tr class="{% cycle 'row1' 'row2' %}"> ... </tr> {% endfor %}
Outside of a loop, give the values a unique name the first time you call it, then use that name each successive time through:
<tr class="{% cycle 'row1' 'row2' 'row3' as rowcolors %}">...</tr> <tr class="{% cycle rowcolors %}">...</tr> <tr class="{% cycle rowcolors %}">...</tr>
You can use any number of values, separated by spaces. Commas can also be used to separate values; if a comma is used, the cycle values are interpreted as literal strings.
The optional flag "silent" can be used to prevent the cycle declaration from returning any value:
{% for o in some_list %} {% cycle 'row1' 'row2' as rowcolors silent %} <tr class="{{ rowcolors }}">{% include "subtemplate.html " %}</tr> {% endfor %}
Output a whole load of debugging information, including the current context and imported modules.
Sample usage:
<pre> {% debug %} </pre>
Filter the contents of the block through variable filters.
Filters can also be piped through each other, and they can have arguments -- just like in variable syntax.
Sample usage:
{% filter force_escape|lower %} This text will be HTML-escaped, and will appear in lowercase. {% endfilter %}
Note that the escape and safe filters are not acceptable arguments. Instead, use the autoescape tag to manage autoescaping for blocks of template code.
Loop over each item in an array.
For example, to display a list of athletes given athlete_list:
<ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} </ul>
You can loop over a list in reverse by using {% for obj in list reversed %}.
You can also unpack multiple values from a two-dimensional array:
{% for key,value in dict.items %} {{ key }}: {{ value }} {% endfor %}
The for tag can take an optional {% empty %} clause that will be displayed if the given array is empty or could not be found:
<ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% empty %} <li>Sorry, no athletes in this list.</li> {% endfor %} <ul>
The above is equivalent to -- but shorter, cleaner, and possibly faster than -- the following:
<ul> {% if athlete_list %} {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} {% else %} <li>Sorry, no athletes in this list.</li> {% endif %} </ul>
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 "above" the current one
Evaluate a variable, and if that variable is "true" (i.e., exists, is not empty, and is not a false boolean value), output the contents of the block:
{% if athlete_list %} Number of athletes: {{ athlete_list|count }} {% elif athlete_in_locker_room_list %} Athletes should be out of the locker room soon! {% else %} No athletes. {% endif %}
In the above, if athlete_list is not empty, the number of athletes will be displayed by the {{ athlete_list|count }} variable.
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.
if tags may use or, and or not to test a number of variables or to negate a given variable:
{% if not athlete_list %} There are no athletes. {% endif %} {% if athlete_list or coach_list %} There are some athletes or some coaches. {% endif %} {% if athlete_list and coach_list %} Both athletes and coaches are available. {% endif %} {% if not athlete_list or coach_list %} There are no athletes, or there are some coaches. {% endif %} {% if athlete_list and not coach_list %} There are some athletes and absolutely no coaches. {% endif %}
Comparison operators are also available, and the use of filters is also allowed, for example:
{% if articles|length >= 5 %}...{% endif %}
Arguments and operators _must_ have a space between them, so {% if 1>2 %} is not a valid if tag.
All supported operators are: or, and, in, not in ==, !=, >, >=, < and <=.
Operator precedence follows Python.
Add one or more values to the context (inside of this block) for caching and easy access.
For example:
{% with total=person.some_sql_method %} {{ total }} object{{ total|pluralize }} {% endwith %}
Multiple values can be added to the context:
{% with foo=1 bar=2 %} ... {% endwith %}
The legacy format of {% with person.some_sql_method as total %} is still accepted.
Output the first variable passed that is not False.
Output nothing if all the passed variables are False.
Sample usage:
{% firstof var1 var2 var3 as myvar %}
This is equivalent to:
{% if var1 %} {{ var1 }} {% elif var2 %} {{ var2 }} {% elif var3 %} {{ var3 }} {% endif %}
but much cleaner!
You can also use a literal string as a fallback value in case all passed variables are False:
{% firstof var1 var2 var3 "fallback value" %}
If you want to disable auto-escaping of variables you can use:
{% autoescape off %} {% firstof var1 var2 var3 "<strong>fallback value</strong>" %} {% autoescape %}
Or if only some variables should be escaped, you can use:
{% firstof var1 var2|safe var3 "<strong>fallback value</strong>"|safe %}
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.
Check its own rendered contents against its previous state and only displays the content if it has changed. For example, this displays a list of days, only displaying the month if it changes:
<h1>Archive for {{ year }}</h1> {% for date in days %} {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %} <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a> {% endfor %}
If given one or more variables, check whether any variable has changed. For example, the following shows the date every time it changes, while showing the hour if either the hour or the date has changed:
{% for date in days %} {% ifchanged date.date %} {{ date.date }} {% endifchanged %} {% ifchanged date.hour date.date %} {{ date.hour }} {% endifchanged %} {% endfor %}
Load a custom template tag library into the parser.
For example, to load the template tags in django/templatetags/news/photos.py:
{% load news.photos %}
Can also be used to load an individual tag/filter from a library:
{% load byline from news %}
Create random Latin text useful for providing test data in templates.
Usage format:
{% lorem [count] [method] [random] %}
count is a number (or variable) containing the number of paragraphs or words to generate (default is 1).
method is either w for words, p for HTML paragraphs, b for plain-text paragraph blocks (default is b).
random is the word random, which if given, does not use the common paragraph (starting "Lorem ipsum dolor sit amet, consectetuer...").
Examples:
Display the date, formatted according to the given string.
Use the same format as PHP's date() function; see https://php.net/date for all the possible values.
Sample usage:
It is {% now "jS F Y H:i" %}
Regroup a list of alike objects by a common attribute.
This complex tag is best illustrated by use of an example: say that musicians is a list of Musician objects that have name and instrument attributes, and you'd like to display a list that looks like:
- Guitar:
- Django Reinhardt
- Emily Remler
- Piano:
- Lovie Austin
- Bud Powell
- Trumpet:
- Duke Ellington
The following snippet of template code would accomplish this dubious task:
{% regroup musicians by instrument as grouped %} <ul> {% for group in grouped %} <li>{{ group.grouper }} <ul> {% for musician in group.list %} <li>{{ musician.name }}</li> {% endfor %} </ul> {% endfor %} </ul>
As you can see, {% regroup %} populates a variable with a list of objects with grouper and list attributes. grouper contains the item that was grouped by; list contains the list of objects that share that grouper. In this case, grouper would be Guitar, Piano and Trumpet, and list is the list of musicians who play this instrument.
Note that {% regroup %} does not work when the list to be grouped is not sorted by the key you are grouping by! This means that if your list of musicians was not sorted by instrument, you'd need to make sure it is sorted before using it, i.e.:
{% regroup musicians|dictsort:"instrument" by instrument as grouped %}
Reset a cycle tag.
If an argument is given, reset the last rendered cycle tag whose name matches the argument, else reset the last rendered cycle tag (named or unnamed).
Remove whitespace between HTML tags, including tab and newline characters.
Example usage:
{% spaceless %} <p> <a href="foo/">Foo</a> </p> {% endspaceless %}
This example returns this HTML:
<p><a href="foo/">Foo</a></p>
Only space between tags is normalized -- not space between tags and text. In this example, the space around Hello isn't stripped:
{% spaceless %} <strong> Hello </strong> {% endspaceless %}
Output one of the bits 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 Outputs openblock {% closeblock %} openvariable {{ closevariable }} openbrace { closebrace } opencomment {# closecomment #}
Return an absolute URL matching the given view with its parameters.
This is a way to define links that aren't tied to a particular URL configuration:
{% url "url_name" arg1 arg2 %} or {% url "url_name" name1=value1 name2=value2 %}
The first argument is a URL pattern name. Other arguments are space-separated values that will be filled in place of positional and keyword arguments in the URL. Don't mix positional and keyword arguments. All arguments for the URL must be present.
For example, if you have a view app_name.views.client_details taking the client's id and the corresponding line in a URLconf looks like this:
path('client/<int:id>/', views.client_details, name='client-detail-view')
and this app's URLconf is included into the project's URLconf under some path:
path('clients/', include('app_name.urls'))
then in a template you can create a link for a certain client like this:
{% url "client-detail-view" client.id %}
The URL will look like /clients/client/123/.
The first argument may also be the name of a template variable that will be evaluated to obtain the view name or the URL name, e.g.:
{% with url_name="client-detail-view" %} {% url url_name client.id %} {% endwith %}
Stop the template engine from rendering the contents of this block tag.
Usage:
{% verbatim %} {% don't process this %} {% endverbatim %}
You can also designate a specific closing tag block (allowing the unrendered use of {% endverbatim %}):
{% verbatim myblock %} ... {% endverbatim myblock %}
For creating bar charts and such. Calculate the ratio of a given value to a maximum value, and then apply that ratio to a constant.
For example:
<img src="bar.png" alt="Bar" height="10" width="{% widthratio this_value max_value max_width %}">
If this_value is 175, max_value is 200, and max_width is 100, the image in the above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88).
In some cases you might want to capture the result of widthratio in a variable. It can be useful for instance in a blocktranslate like this:
{% widthratio this_value max_value max_width as width %} {% blocktranslate %}The width is: {{ width }}{% endblocktranslate %}