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
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.
# ← name of the app
templatetags/
__init__.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 = [
# …,
,
# …,
]
You furthermore need to register the template tag:
# app_name/templatetags/extra.py
from django import template
register = template.Library()
# ← 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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.