views:

162

answers:

1

how to use the templatetag of django app?

+3  A: 

Creating a new template tag can be quite involved depending on what it does, and whether or not it is a block tag (with a start and an end -- like {% if %} {% endif %}, etc.) Basically, you need to create a example.templatetags module (where example is your application) which implements your tag, and then {% load example %} in your templates so that they can "see" your template tags and filters.

For example, if you want to create a {% foobarbaz %} tag which outputs the either "foor" or "bar" or "baz" (when given as the arg) or "" (when anything else is given) when used in a template, your example/templatetags.py might looks like this:

from django import template
register = template.Library()

@register.simple_tag
def foobarbaz(input):
    if "foo" == input:
        return "foo"
    if "bar" == input:
        return "bar"
    if "baz" == input:
        return "baz"
    return ""

In your templates, you might do something like this (remembering that the above module is part of the example application):

{% load example %}
{% foobarbaz "bar" %}
{% foobarbaz "elephant" %}
{% foobarbaz "foo" %}

Which would output:

bar

foo

Note that, as I'm using simple_tag, I have only rudimentary control over the parsing of arguments, there's no way to do an end tag, etc.

See the documentation on custom template filters and tags for more information.

thsutton