Reputation: 35
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
Upvotes: 1
Views: 325
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