Jhan Carlos Holguin
Jhan Carlos Holguin

Reputation: 35

How to create a custom templatetag in my django project

I have been trying create a custom templatetag in my project , but it does not work

This is my structured project :

I created a folder in my index directory called templatetags > __init__.py , extras.py , inside extras file this:

from django import template
register = template.Library()
def cut(value):
   return value.replace("no", 'yes')

Template : {% load poll_extras %}

but I got this

Error

Upvotes: 1

Views: 325

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

I created a folder in my index directory called templatetags > __init__.py , extras.py , inside extras file this.

You should add this to an app. So in the root directory, you have the directory of the app, and under that app directory you create a templatetags directory.

app_name  # ← name of the app
    templatetags/
        __init__.py
        extra.py

This app should be an installed app, so you add the name of the app in the INSTALLED_APPS setting [Django-doc]:

# settings.py

INSTALLED_APP = [
    # …,
    'app_name',
    # …,
]

You furthermore need to register the template tag:

# app_name/templatetags/extra.py

from django import template
register = template.Library()

@register.tag  # ← register the template tag
def cut(value):
   return value.replace("no", 'yes')

You should use @register.filter in case you want to register a template filter, instead of a template tag.

Upvotes: 2

Related Questions