how do i create a custom templatetag in my django project?

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  # &leftarrow 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  # &leftarrow 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.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top