Django Simple tags


Example

The simplest way of defining a custom template tag is to use a simple_tag. These are very straightforward to setup. The function name will be the tag name (though you can override it), and arguments will be tokens ("words" separated by spaces, except spaces enclosed between quotes). It even supports keyword arguments.

Here is a useless tag that will illustrate our example:

{% useless 3 foo 'hello world' foo=True bar=baz.hello|capfirst %}

Let foo and baz be context variables like the following:

{'foo': "HELLO", 'baz': {'hello': "world"}}

Say we want this very useless tag to render like this:

HELLO;hello world;bar:World;foo:True<br/>
HELLO;hello world;bar:World;foo:True<br/>
HELLO;hello world;bar:World;foo:True<br/>

Kind of arguments concatenation repeated 3 times (3 being the first argument).

Here is what the tag implementation may look like:

from django.utils.html import format_html_join

@register.simple_tag
def useless(repeat, *args, **kwargs):
    output = ';'.join(args + ['{}:{}'.format(*item) for item in kwargs.items()])
    outputs = [output] * repeat
    return format_html_join('\n', '{}<br/>', ((e,) for e in outputs))

format_html_join allows to mark <br/> as safe HTML, but not the content of outputs.