Syntax

A Maile template is simply a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags.

A template is rendered with a context. Rendering replaces variables with their values, which are looked up in the context, and executes tags. Everything else is output as is.

The syntax of the maile template language involves four constructs.

Templates

A template is simply a text file. It can generate any text-based format (HTML, XML, CSV, etc.).

A template contains variables, which get replaced with values when the template is evaluated, and tags, which control the logic of the template.

Below is a minimal template that illustrates a few basics. Each element will be explained later in this document.

{% extends "base_generic.html" %}

{% block title %}{{ section.title }}{% endblock %}

{% block content %}
<h1>{{ section.title }}</h1>

{% for story in story_list %}
<h2>
  <a href="{{ story.get_absolute_url }}">
    {{ story.headline|upper }}
  </a>
</h2>
<p>{{ story.tease|truncatewords:"100" }}</p>
{% endfor %}
{% endblock %}

Variables

A variable outputs a value from the context, which is a dict-like object mapping keys to values.

Variables are surrounded by {{ and }} like this:

My first name is {{ first_name }}. My last name is {{ last_name }}.

With a context of {‘first_name’: ‘Richard’, ‘last_name’: ‘Hendricks’}, this template renders to:

My first name is Richard. My last name is Hendricks. 

Dictionary lookup, attribute lookup and list-index lookups are implemented with a dot notation:

{{ my_dict.key }}
{{ my_object.attribute }}
{{ my_list.0 }}

If a variable resolves to a callable, the template system will call it with no arguments and use its result instead of the callable.

Tags

Tags provide arbitrary logic in the rendering process.

This definition is deliberately vague. For example, a tag can output content, serve as a control structure e.g. an “if” statement or a “for” loop, grab content from a database, or even enable access to other template tags.

Tags are surrounded by {% and %} like this:

{% email %}

Most tags accept arguments:

{% cycle 'odd' 'even' %}

Some tags require beginning and ending tags:

{% if user.is_authenticated %}Hello, {{ user.username }}.{% endif %}

Filters

Filters transform the values of variables and tag arguments.

They look like this:

{{ maile|title }}

With a context of {‘maile’: ‘simple marketing and transactional emails’}, this template renders to:

Simple Marketing And Transactional Emails

Some filters take an argument:

{{ my_date|date:"Y-m-d" }}

Comments

Comments look like this:

{# this won't be rendered #}

A {% comment %} tag provides multi-line comments.

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.

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

comment tags cannot be nested.

Built-in template tags and filters

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:

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

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

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

{% for o in some_list %}
    <tr class="{% cycle rowvalue1 rowvalue2 %}">
        ...
    </tr>
{% endfor %}

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

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

You can mix variables and strings:

{% for o in some_list %}
    <tr class="{% cycle 'row1' rowvalue2 'row3' %}">
        ...
    </tr>
{% endfor %}

In some cases you might want to refer to the current value of a cycle without advancing to the next value. To do this, just give the {% cycle %} tag a name, using “as”, like this:

{% cycle 'row1' 'row2' as rowcolors %}
<tr>
    <td class="{% cycle 'row1' 'row2' as rowcolors %}">...</td>
    <td class="{{ rowcolors }}">...</td>
</tr>
<tr>
    <td class="{% cycle rowcolors %}">...</td>
    <td class="{{ rowcolors }}">...</td>
</tr>
<tr>
    <td class="row1">...</td>
    <td class="row1">...</td>
</tr>
<tr>
    <td class="row2">...</td>
    <td class="row2">...</td>
</tr>

extends

Signals that this template extends a parent template.

This tag can be used in two ways:

  • {% extends “base” %} (with quotes) uses the literal value “base” as the name of the parent template to extend.
  • {% extends variable %} uses the value of variable. If the variable evaluates to a string, maile will use that string as the name of the parent template. If the variable evaluates to a Template object, maile will use that object as the parent template.

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.

Sample usage:

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

firstof

Outputs the first argument variable that is not False. Outputs nothing if all the passed variables are False.

Sample usage:

{% firstof var1 var2 var3 %}

This is equivalent to:

{% if var1 %}
    {{ var1 }}
{% elif var2 %}
    {{ var2 }}
{% elif var3 %}
    {{ var3 }}
{% endif %}

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

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

for

Loops over each item in an array, making the item available in a context variable. For example, to display a list of athletes provided in products_list:

<ul>
{% for product in products_list %}
    <li>{{ product.name }}</li>
{% endfor %}
</ul>

You can loop over a list in reverse by using {% for obj in list reversed %}.

If you need to loop over a list of lists, you can unpack the values in each sublist into individual variables. For example, if your context contains a list of (x,y) coordinates called points, you could use the following to output the list of points:

{% for x, y in points %}
    There is a point at {{ x }},{{ y }}
{% endfor %}

This can also be useful if you need to access the items in a dictionary. For example, if your context contained a dictionary data, the following would display the keys and values of the dictionary:

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

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:

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

if

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:

{% if product_list %}
    Number of products: {{ product_list|length }}
{% elif hidden_product_list %}
    Hidden products in a list
{% else %}
    No products.
{% endif %}

In the above, if product_list is not empty, the number of products will be displayed by the {{ product_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:

{% if product_list and user_list %}
    Both products and users are available.
{% endif %}
{% if not product_list %}
    There are no products.
{% endif %}
{% if product_list or user_list %}
    There are some products or some users.
{% endif %}
{% if not product_list or user_list %}
    There are no products or there are some users.
{% endif %}
{% if product_list and not user_list %}
    There are some products and absolutely no users.
{% endif %}

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

{% if product_list and user_list or order_list %}

will be interpreted like:

if (product_list and user_list) or order_list

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

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

== operator

Equality. Example:

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

Inequality. Example:

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

Less than. Example:

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

Greater than. Example:

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

Less than or equal to. Example:

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

Greater than or equal to. Example:

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

Contained within. This operator is supported by many Python containers to test whether the given value is in the container. The following are some examples of how x in y will be interpreted:

{% if "bc" in "abcdef" %}
  This appears since "bc" is a substring of "abcdef"
{% endif %}
{% if "hello" in greetings %}
  If greetings is a list or set, one element of which is the string
  "hello", this will appear.
{% endif %}
{% if user in users %}
  If users is a QuerySet, this will appear if user is an
  instance that belongs to the QuerySet.
{% endif %}
not in operator

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

is operator

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

{% if somevar is True %}
  This appears if and only if somevar is True.
{% endif %}
{% if somevar is None %}
  This appears if somevar is None, or if somevar is not found in the context.
{% endif %}
is not operator

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

{% if somevar is not True %}
  This appears if somevar is not True, or if somevar is not found in the
  context.
{% endif %}
{% if somevar is not None %}
  This appears if and only if somevar is not None.
{% endif %}

Filters

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

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

Complex expressions

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

  • or
  • and
  • not
  • in
  • ==, !=, <, >, <=, >=
{% if a == b or c == d and e %}

…will be interpreted as:

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

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

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

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

you should use:

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

ifchanged

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

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

  1. Checks its own rendered contents against its previous state and only displays the content if it has changed. For example, this displays a list of days, only displaying the month if it changes:

    ```django
    <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:

    ```django
    {% for date in days %}
        {% ifchanged date.date %} {{ date.date }} {% endifchanged %}
        {% ifchanged date.hour date.date %}
            {{ date.hour }}
        {% endifchanged %}
    {% endfor %}
    ```
    

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

{% for match in matches %}
    <div style="background-color:
        {% ifchanged match.ballot_id %}
            {% cycle "red" "blue" %}
        {% else %}
            gray
        {% endifchanged %}
    ">{{ match }}</div>
{% endfor %}

include

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

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

This example includes the contents of the template “bar”:

{% include "bar" %}

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

{% include template_name %}

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

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

Context: variable person is set to “John” and variable greeting is set to “Hello”.

Template:

{% include "name-snippet" %}

The name-snippet template:

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

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

{% include "name-snippet" with person="Jane" greeting="Hello" %}

If you want to render the context only with the variables provided (or even no variables at all), use the only option. No other variables are available to the included template:

{% include "name-snippet" with greeting="Hi" only %}

now

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

Example:

It is {% now "jS F Y H:i" %}

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

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

This would display as “It is the 4th of September”.

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 blocktrans for example:

{% now "Y" as current_year %}
{% blocktrans %}Copyright {{ current_year }}{% endblocktrans %}

spaceless

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

Example usage:

{% spaceless %}
    <p>
        <a href="foo/">Foo</a>
    </p>
{% endspaceless %}

This example would return this HTML:

<p><a href="foo/">Foo</a></p>

Only space between tags is removed – not space between tags and text. In this example, the space around Hello won’t be stripped:

{% spaceless %}
    <strong>
        Hello
    </strong>
{% endspaceless %}

url

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

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

{% url 'some-url-name' v1 v2 %}

The first argument is a URL pattern name. It can be a quoted literal or any other context variable. Additional arguments are optional and should be space-separated values that will be used as arguments in the URL. The example above shows passing positional arguments. Alternatively you may use keyword syntax:

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

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

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:

{% verbatim %}
    {{if dying}}Still alive.{{/if}}
{% endverbatim %}

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

{% verbatim myblock %}
    Avoid template rendering via the {% verbatim %}{% endverbatim %} block.
{% endverbatim myblock %}

widthratio

For creating bar charts and such, this tag calculates the ratio of a given value to a maximum value, and then applies that ratio to a constant.

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 175200 = .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 %}

with

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

For example:

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

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

You can assign more than one context variable:

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

Built-in filter reference

add

Adds the argument to the value.

For example:

{{ value|add:"2" }}

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

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

For example, if we have:

{{ first|add:second }}

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

addslashes

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

For example:

{{ value|addslashes }}

If value is “I’m using Django”, the output will be “I\’m using Django”.

capfirst

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

For example:

{{ value|capfirst }}

If value is “maile”, the output will be “Maile”.

center

Centers the value in a field of a given width.

For example:

{{ value|center:"15" }}

If value is “Maile”, the output will be ” Maile “.

cut

Removes all values of arg from the given string.

For example:

{{ value|cut:" " }}

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

date

Formats a date according to the given format.

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

For example:

{{ value|date:"D d M Y" }}

If value is a datetime object (e.g., the result of datetime.datetime.now()), the output will be the string ‘Wed 09 Jan 2008’.

default

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

For example:

{{ value|default:"nothing" }}

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

default_if_none

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

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

For example:

{{ value|default_if_none:"nothing" }}

If value is None, the output will be nothing.

divisibleby

Returns True if the value is divisible by the argument.

For example:

{{ value|divisibleby:"3" }}

If value is 21, the output would be True.

escape

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

  • < is converted to <
  • > is converted to >
  • ’ (single quote) is converted to '
  • ” (double quote) is converted to "
  • & is converted to &

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

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

{% autoescape off %}
    {{ title|escape }}
{% endautoescape %}

first

Returns the first item in a list.

For example:

{{ value|first }}

If value is the list [‘a’, ‘b’, ‘c’], the output will be ‘a’.

floatformat

When used without an argument, rounds a floating-point number to one decimal place – but only if there’s a decimal part to be displayed. For example:

value Template Output
34.23234 {{ value|floatformat }} 34.2
34.00000 {{ value|floatformat }} 34
34.26000 {{ value|floatformat }} 34.3

If used with a numeric integer argument, floatformat rounds a number to that many decimal places. For example:

value Template Output
34.23234 {{ value|floatformat:3 }} 34.232
34.00000 {{ value|floatformat:3 }} 34.000
34.26000 {{ value|floatformat:3 }} 34.260

Particularly useful is passing 0 (zero) as the argument which will round the float to the nearest integer.

value Template Output
34.23234 {{ value|floatformat:“0” }} 34
34.00000 {{ value|floatformat:“0” }} 34
39.56000 {{ value|floatformat:“0” }} 40

If the argument passed to floatformat is negative, it will round a number to that many decimal places – but only if there’s a decimal part to be displayed. For example:

value Template Output
34.23234 {{ value|floatformat:“-3” }} 34.232
34.00000 {{ value|floatformat:“-3” }} 34
34.26000 {{ value|floatformat:“-3” }} 34.260

get_digit

Given a whole number, returns the requested digit, where 1 is the right-most digit, 2 is the second-right-most digit, etc. Returns the original value for invalid input (if input or argument is not an integer, or if argument is less than 1). Otherwise, output is always an integer.

For example:

{{ value|get_digit:"2" }}

If value is 123456789, the output will be 8.

iriencode

Converts an IRI (Internationalized Resource Identifier) to a string that is suitable for including in a URL. This is necessary if you’re trying to use strings containing non-ASCII characters in a URL.

It’s safe to use this filter on a string that has already gone through the urlencode filter.

For example:

{{ value|iriencode }}

If value is ”?test=1&me=2”, the output will be ”?test=1&me=2”.

join

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

For example:

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

If value is the list [‘a’, ‘b’, ‘c’], the output will be the string “a // b // c”.

last

Returns the last item in a list.

For example:

{{ value|last }}

If value is the list [‘a’, ‘b’, ‘c’, ’d’], the output will be the string “d”.

length

Returns the length of the value. This works for both strings and lists.

For example:

{{ value|length }}

If value is [‘a’, ‘b’, ‘c’, ’d’] or “abcd”, the output will be 4.

The filter returns 0 for an undefined variable.

length_is

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

For example:

{{ value|length_is:"4" }}

If value is [‘a’, ‘b’, ‘c’, ’d’] or “abcd”, the output will be true.

linebreaks

Replaces line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (
) and a new line followed by a blank line becomes a paragraph break (

).

For example:

{{ value|linebreaks }}

If value is Joel\nis a slug, the output will be

Joel
is a slug

.

linebreaksbr

Converts all newlines in a piece of plain text to HTML line breaks (
).

For example:

{{ value|linebreaksbr }}

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

ljust

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

Argument: field size

For example:

{{ value|ljust:"10" }}
````
If value is **Maile**, the output will be **"Maile    "**.


### lower
Converts a string into all lowercase.

For example:

```django
{{ value|lower }}

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

pluralize

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

Example:

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

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

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

Example:

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

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

Example:

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

random

Returns a random item from the given list.

For example:

{{ value|random }}

If value is the list [‘a’, ‘b’, ‘c’, ’d’], the output could be “b”.

rjust

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

Argument: field size

For example:

{{ value|rjust:"10" }}

If value is Maile, the output will be ” Django”.

slice

Returns a slice of the list.

Uses the same syntax as Python’s list slicing. See https://www.diveinto.org/python3/native-datatypes.html#slicinglists for an introduction.

Example:

{{ some_list|slice:":2" }}

If some_list is **[‘a’, ‘b’, ‘c’], the output will be [‘a’, ‘b’].

slugify

Converts to ASCII. Converts spaces to hyphens. Removes characters that aren’t alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace.

For example:

{{ value|slugify }} If value is “Joel is a slug”, the output will be “joel-is-a-slug”.

timesince

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

Takes an optional argument that is a variable containing the date to use as the comparison point (without the argument, the comparison point is now). For example, if blog_date is a date instance representing midnight on 1 June 2006, and comment_date is a date instance for 08:00 on 1 June 2006, then the following would return “8 hours”:

{{ blog_date|timesince:comment_date }}

Comparing offset-naive and offset-aware datetimes will return an empty string.

Minutes is the smallest unit used, and “0 minutes” will be returned for any date that is in the future relative to the comparison point.

timeuntil

Similar to timesince, except that it measures the time from now until the given date or datetime. For example, if today is 1 June 2006 and conference_date is a date instance holding 29 June 2006, then {{ conference_date|timeuntil }} will return “4 weeks”.

Takes an optional argument that is a variable containing the date to use as the comparison point (instead of now). If from_date contains 22 June 2006, then the following will return “1 week”:

{{ conference_date|timeuntil:from_date }}

Comparing offset-naive and offset-aware datetimes will return an empty string.

Minutes is the smallest unit used, and “0 minutes” will be returned for any date that is in the past relative to the comparison point.

title

Converts a string into titlecase by making words start with an uppercase character and the remaining characters lowercase. This tag makes no effort to keep “trivial words” in lowercase.

For example:

{{ value|title }}

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

truncatechars

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

Argument: Number of characters to truncate to

For example:

{{ value|truncatechars:7 }}

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

truncatewords

Truncates a string after a certain number of words.

Argument: Number of words to truncate after

For example:

{{ value|truncatewords:2 }}

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

Newlines within the string will be removed.

upper

Converts a string into all uppercase.

For example:

{{ value|upper }}

If value is “Joel is a slug”, the output will be “JOEL IS A SLUG”.

urlencode

Escapes a value for use in a URL.

For example:

{{ value|urlencode }}

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

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

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

{{ value|urlencode:"" }}

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

wordcount

Returns the number of words.

For example:

{{ value|wordcount }}

If value is “Joel is a slug”, the output will be 4.

wordwrap

Wraps words at specified line length.

Argument: number of characters at which to wrap the text

For example:

{{ value|wordwrap:5 }}

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

Joel
is a
slug

yesno

Maps values for true, false, and (optionally) none, to the strings “yes”, “no”, “maybe”, or a custom mapping passed as a comma-separated list, and returns one of those strings according to the value:

For example:

{{ value|yesno:"yeah,no,maybe" }}
Value Argument Outputs
True yes
True “yeah,no,maybe” yeah
False “yeah,no,maybe” no
None “yeah,no,maybe” maybe
None “yeah,no” no (converts None to False if no mapping for None is given)