3. Django template tags

django.templatetags.cache.do_cache(parser, token)

This will cache the contents of a template fragment for a given amount of time.

Usage:

{% load cache %}
{% cache [expire_time] [fragment_name] %}
    .. some expensive processing ..
{% endcache %}

This tag also supports varying by a list of arguments:

{% load cache %}
{% cache [expire_time] [fragment_name] [var1] [var2] .. %}
    .. some expensive processing ..
{% endcache %}

Optionally the cache to use may be specified thus:

{% cache ....  using="cachename" %}

Each unique set of arguments will result in a unique cache entry.

django.templatetags.i18n.do_block_translate(parser, token)

Translate a block of text with parameters.

Usage:

{% blocktrans with bar=foo|filter boo=baz|filter %}
This is {{ bar }} and {{ boo }}.
{% endblocktrans %}

Additionally, this supports pluralization:

{% blocktrans count count=var|length %}
There is {{ count }} object.
{% plural %}
There are {{ count }} objects.
{% endblocktrans %}

This is much like ngettext, only in template syntax.

The “var as value” legacy format is still supported:

{% blocktrans with foo|filter as bar and baz|filter as boo %}
{% blocktrans count var|length as count %}

The translated string can be stored in a variable using asvar:

{% blocktrans with bar=foo|filter boo=baz|filter asvar var %}
This is {{ bar }} and {{ boo }}.
{% endblocktrans %}
{{ var }}

Contextual translations are supported:

{% blocktrans with bar=foo|filter context "greeting" %}
    This is {{ bar }}.
{% endblocktrans %}

This is equivalent to calling pgettext/npgettext instead of (u)gettext/(u)ngettext.

django.templatetags.i18n.do_get_available_languages(parser, token)

Store a list of available languages in the context.

Usage:

{% get_available_languages as languages %}
{% for language in languages %}
...
{% endfor %}

This puts settings.LANGUAGES into the named variable.

django.templatetags.i18n.do_get_current_language(parser, token)

Store the current language in the context.

Usage:

{% get_current_language as language %}

This fetches the currently active language and puts its value into the language context variable.

django.templatetags.i18n.do_get_current_language_bidi(parser, token)

Store the current language layout in the context.

Usage:

{% get_current_language_bidi as bidi %}

This fetches the currently active language’s layout and puts its value into the bidi context variable. True indicates right-to-left layout, otherwise left-to-right.

django.templatetags.i18n.do_get_language_info(parser, token)

Store the language information dictionary for the given language code in a context variable.

Usage:

{% get_language_info for LANGUAGE_CODE as l %}
{{ l.code }}
{{ l.name }}
{{ l.name_translated }}
{{ l.name_local }}
{{ l.bidi|yesno:"bi-directional,uni-directional" }}
django.templatetags.i18n.do_get_language_info_list(parser, token)

Store a list of language information dictionaries for the given language codes in a context variable. The language codes can be specified either as a list of strings or a settings.LANGUAGES style list (or any sequence of sequences whose first items are language codes).

Usage:

{% get_language_info_list for LANGUAGES as langs %}
{% for l in langs %}
  {{ l.code }}
  {{ l.name }}
  {{ l.name_translated }}
  {{ l.name_local }}
  {{ l.bidi|yesno:"bi-directional,uni-directional" }}
{% endfor %}
django.templatetags.i18n.do_translate(parser, token)

Mark a string for translation and translate the string for the current language.

Usage:

{% trans "this is a test" %}

This marks the string for translation so it will be pulled out by makemessages into the .po files and runs the string through the translation engine.

There is a second form:

{% trans "this is a test" noop %}

This marks the string for translation, but returns the string unchanged. Use it when you need to store values into forms that should be translated later on.

You can use variables instead of constant strings to translate stuff you marked somewhere else:

{% trans variable %}

This tries to translate the contents of the variable variable. Make sure that the string in there is something that is in the .po file.

It is possible to store the translated string into a variable:

{% trans "this is a test" as var %}
{{ var }}

Contextual translations are also supported:

{% trans "this is a test" context "greeting" %}

This is equivalent to calling pgettext instead of (u)gettext.

django.templatetags.i18n.language(parser, token)

Enable the given language just for this block.

Usage:

{% language "de" %}
    This is {{ bar }} and {{ boo }}.
{% endlanguage %}

Default tags used by the template system, available to all templates.

class django.template.defaulttags.AutoEscapeControlNode(setting, nodelist)

Implement the actions of the autoescape tag.

render(context)

Return the node rendered as a string.

class django.template.defaulttags.GroupedResult(grouper, list)
grouper

Alias for field number 0

list

Alias for field number 1

class django.template.defaulttags.TemplateLiteral(value, text)
display()

Return what to display in error messages for this node

django.template.defaulttags.autoescape(parser, token)

Force autoescape behavior for this block.

django.template.defaulttags.comment(parser, token)

Ignore everything between {% comment %} and {% endcomment %}.

django.template.defaulttags.cycle(parser, token)

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 %}
django.template.defaulttags.debug(parser, token)

Output a whole load of debugging information, including the current context and imported modules.

Sample usage:

<pre>
    {% debug %}
</pre>
django.template.defaulttags.do_filter(parser, token)

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.

django.template.defaulttags.do_for(parser, token)

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
django.template.defaulttags.do_if(parser, token)

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.

django.template.defaulttags.do_with(parser, token)

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.

django.template.defaulttags.firstof(parser, token)

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 obviously 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 %}
django.template.defaulttags.ifchanged(parser, token)

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

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

  1. 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 %}
    
  2. If given one or more variables, check whether any variable has changed. For example, the following shows the date every time it changes, while showing the hour if either the hour or the date has changed:

    {% for date in days %}
        {% ifchanged date.date %} {{ date.date }} {% endifchanged %}
        {% ifchanged date.hour date.date %}
            {{ date.hour }}
        {% endifchanged %}
    {% endfor %}
    
django.template.defaulttags.ifequal(parser, token)

Output the contents of the block if the two arguments equal each other.

Examples:

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

{% ifnotequal user.id comment.user_id %}
    ...
{% else %}
    ...
{% endifnotequal %}
django.template.defaulttags.ifnotequal(parser, token)

Output the contents of the block if the two arguments are not equal. See ifequal.

django.template.defaulttags.load(parser, token)

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 %}
django.template.defaulttags.load_from_library(library, label, names)

Return a subset of tags and filters from a library.

django.template.defaulttags.lorem(parser, token)

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:

  • {% lorem %} outputs the common “lorem ipsum” paragraph
  • {% lorem 3 p %} outputs the common “lorem ipsum” paragraph and two random paragraphs each wrapped in HTML <p> tags
  • {% lorem 2 w random %} outputs two random latin words
django.template.defaulttags.now(parser, token)

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" %}
django.template.defaulttags.regroup(parser, token)

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 %}
django.template.defaulttags.resetcycle(parser, token)

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

django.template.defaulttags.spaceless(parser, token)

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 %}
django.template.defaulttags.templatetag(parser, token)

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 #}
django.template.defaulttags.url(parser, token)

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 %}
django.template.defaulttags.verbatim(parser, token)

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 %}
django.template.defaulttags.widthratio(parser, token)

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 blocktrans like this:

{% widthratio this_value max_value max_width as width %}
{% blocktrans %}The width is: {{ width }}{% endblocktrans %}

Default variable filters.

django.template.defaultfilters.add(value, arg)

Add the arg to the value.

django.template.defaultfilters.addslashes(value)

Add slashes before quotes. Useful for escaping strings in CSV, for example. Less useful for escaping JavaScript; use the escapejs filter instead.

django.template.defaultfilters.capfirst(value)

Capitalize the first character of the value.

django.template.defaultfilters.center(value, arg)

Center the value in a field of a given width.

django.template.defaultfilters.cut(value, arg)

Remove all values of arg from the given string.

django.template.defaultfilters.date(value, arg=None)

Format a date according to the given format.

django.template.defaultfilters.default(value, arg)

If value is unavailable, use given default.

django.template.defaultfilters.default_if_none(value, arg)

If value is None, use given default.

django.template.defaultfilters.dictsort(value, arg)

Given a list of dicts, return that list sorted by the property given in the argument.

django.template.defaultfilters.dictsortreversed(value, arg)

Given a list of dicts, return that list sorted in reverse order by the property given in the argument.

django.template.defaultfilters.divisibleby(value, arg)

Return True if the value is divisible by the argument.

django.template.defaultfilters.escape_filter(value)

Mark the value as a string that should be auto-escaped.

django.template.defaultfilters.escapejs_filter(value)

Hex encode characters for use in JavaScript strings.

django.template.defaultfilters.filesizeformat(bytes_)

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

django.template.defaultfilters.first(value)

Return the first item in a list.

django.template.defaultfilters.floatformat(text, arg=-1)

Display a float to a specified number of decimal places.

If called without an argument, display the floating point number with one decimal place – but only if there’s a decimal place to be displayed:

  • num1 = 34.23234
  • num2 = 34.00000
  • num3 = 34.26000
  • {{ num1|floatformat }} displays “34.2”
  • {{ num2|floatformat }} displays “34”
  • {{ num3|floatformat }} displays “34.3”

If arg is positive, always display exactly arg number of decimal places:

  • {{ num1|floatformat:3 }} displays “34.232”
  • {{ num2|floatformat:3 }} displays “34.000”
  • {{ num3|floatformat:3 }} displays “34.260”

If arg is negative, display arg number of decimal places – but only if there are places to be displayed:

  • {{ num1|floatformat:”-3” }} displays “34.232”
  • {{ num2|floatformat:”-3” }} displays “34”
  • {{ num3|floatformat:”-3” }} displays “34.260”

If the input float is infinity or NaN, display the string representation of that value.

django.template.defaultfilters.force_escape(value)

Escape a string’s HTML. Return a new string containing the escaped characters (as opposed to “escape”, which marks the content for later possible escaping).

django.template.defaultfilters.get_digit(value, arg)

Given a whole number, return the requested digit of it, where 1 is the right-most digit, 2 is the second-right-most digit, etc. Return 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.

django.template.defaultfilters.iriencode(value)

Escape an IRI value for use in a URL.

django.template.defaultfilters.join(value, arg, autoescape=True)

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

django.template.defaultfilters.json_script(value, element_id)

Output value JSON-encoded, wrapped in a <script type=”application/json”> tag.

django.template.defaultfilters.last(value)

Return the last item in a list.

django.template.defaultfilters.length(value)

Return the length of the value - useful for lists.

django.template.defaultfilters.length_is(value, arg)

Return a boolean of whether the value’s length is the argument.

django.template.defaultfilters.linebreaks_filter(value, autoescape=True)

Replace 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>).

django.template.defaultfilters.linebreaksbr(value, autoescape=True)

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

django.template.defaultfilters.linenumbers(value, autoescape=True)

Display text with line numbers.

django.template.defaultfilters.ljust(value, arg)

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

django.template.defaultfilters.lower(value)

Convert a string into all lowercase.

django.template.defaultfilters.make_list(value)

Return the value turned into a list.

For an integer, it’s a list of digits. For a string, it’s a list of characters.

django.template.defaultfilters.phone2numeric_filter(value)

Take a phone number and converts it in to its numerical equivalent.

django.template.defaultfilters.pluralize(value, arg='s')

Return a plural suffix if the value is not 1, ‘1’, or an object of length 1. By default, use ‘s’ as the suffix:

  • If value is 0, vote{{ value|pluralize }} display “votes”.
  • If value is 1, vote{{ value|pluralize }} display “vote”.
  • If value is 2, vote{{ value|pluralize }} display “votes”.

If an argument is provided, use that string instead:

  • If value is 0, class{{ value|pluralize:”es” }} display “classes”.
  • If value is 1, class{{ value|pluralize:”es” }} display “class”.
  • If value is 2, class{{ value|pluralize:”es” }} display “classes”.

If the provided argument contains a comma, use the text before the comma for the singular case and the text after the comma for the plural case:

  • If value is 0, cand{{ value|pluralize:”y,ies” }} display “candies”.
  • If value is 1, cand{{ value|pluralize:”y,ies” }} display “candy”.
  • If value is 2, cand{{ value|pluralize:”y,ies” }} display “candies”.
django.template.defaultfilters.pprint(value)

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

django.template.defaultfilters.random(value)

Return a random item from the list.

django.template.defaultfilters.rjust(value, arg)

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

django.template.defaultfilters.safe(value)

Mark the value as a string that should not be auto-escaped.

django.template.defaultfilters.safeseq(value)

A “safe” filter for sequences. Mark each element in the sequence, individually, as safe, after converting them to strings. Return a list with the results.

django.template.defaultfilters.slice_filter(value, arg)

Return a slice of the list using the same syntax as Python’s list slicing.

django.template.defaultfilters.slugify(value)

Convert to ASCII. Convert spaces to hyphens. Remove characters that aren’t alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace.

django.template.defaultfilters.stringfilter(func)

Decorator for filters which should only receive strings. The object passed as the first positional argument will be converted to a string.

django.template.defaultfilters.stringformat(value, arg)

Format the variable according to the arg, a string formatting specifier.

This specifier uses Python string formatting syntax, with the exception that the leading “%” is dropped.

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

django.template.defaultfilters.striptags(value)

Strip all [X]HTML tags.

django.template.defaultfilters.time(value, arg=None)

Format a time according to the given format.

django.template.defaultfilters.timesince_filter(value, arg=None)

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

django.template.defaultfilters.timeuntil_filter(value, arg=None)

Format a date as the time until that date (i.e. “4 days, 6 hours”).

django.template.defaultfilters.title(value)

Convert a string into titlecase.

django.template.defaultfilters.truncatechars(value, arg)

Truncate a string after arg number of characters.

django.template.defaultfilters.truncatechars_html(value, arg)

Truncate HTML after arg number of chars. Preserve newlines in the HTML.

django.template.defaultfilters.truncatewords(value, arg)

Truncate a string after arg number of words. Remove newlines within the string.

django.template.defaultfilters.truncatewords_html(value, arg)

Truncate HTML after arg number of words. Preserve newlines in the HTML.

django.template.defaultfilters.unordered_list(value, autoescape=True)

Recursively take a self-nested list and return an HTML unordered list – WITHOUT opening and closing <ul> tags.

Assume the list is in the proper format. For example, if var contains: ['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']], then {{ var|unordered_list }} returns:

<li>States
<ul>
        <li>Kansas
        <ul>
                <li>Lawrence</li>
                <li>Topeka</li>
        </ul>
        </li>
        <li>Illinois</li>
</ul>
</li>
django.template.defaultfilters.upper(value)

Convert a string into all uppercase.

django.template.defaultfilters.urlencode(value, safe=None)

Escape a value for use in a URL.

The safe parameter determines the characters which should not be escaped by Python’s quote() function. If not provided, use the default safe characters (but an empty string can be provided when all characters should be escaped).

django.template.defaultfilters.urlize(value, autoescape=True)

Convert URLs in plain text into clickable links.

django.template.defaultfilters.urlizetrunc(value, limit, autoescape=True)

Convert URLs into clickable links, truncating URLs to the given character limit, and adding ‘rel=nofollow’ attribute to discourage spamming.

Argument: Length to truncate URLs to.

django.template.defaultfilters.wordcount(value)

Return the number of words.

django.template.defaultfilters.wordwrap(value, arg)

Wrap words at arg line length.

django.template.defaultfilters.yesno(value, arg=None)

Given a string mapping values for true, false, and (optionally) None, return one of those strings according to the value:

Value Argument Outputs
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.
django.template.loader_tags.construct_relative_path(current_template_name, relative_name)

Convert a relative path (starting with ‘./’ or ‘../’) to the full template name based on the current_template_name.

django.template.loader_tags.do_block(parser, token)

Define a block that can be overridden by child templates.

django.template.loader_tags.do_extends(parser, token)

Signal that this template extends a parent template.

This tag may be used in two ways: {% extends "base" %} (with quotes) uses the literal value “base” as the name of the parent template to extend, or {% extends variable %} uses the value of variable as either the name of the parent template to extend (if it evaluates to a string) or as the parent template itself (if it evaluates to a Template object).

django.template.loader_tags.do_include(parser, token)

Load a template and render it with the current context. You can pass additional context using keyword arguments.

Example:

{% include "foo/some_include" %}
{% include "foo/some_include" with bar="BAZZ!" baz="BING!" %}

Use the only argument to exclude the current context when rendering the included template:

{% include "foo/some_include" only %}
{% include "foo/some_include" with bar="1" only %}