Django Template Tags and Filters Simple tags

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any Django Question?