Is it possible to override an existing Django Template Tag or is it necessary to customize the template file and create a new Template Tag?
I was looking for the same answer, so figured I'd share my solution here. I wanted to override the default url template tag in django without having to use a custom template tag and load it in every template file.
The goal was to replace %20 (spaces) with + (pluses). Here's what I came up with...
In __init__.py
from django.template.defaulttags import URLNode
old_render = URLNode.render
def new_render(cls, context):
""" Override existing url method to use pluses instead of spaces
"""
return old_render(cls, context).replace("%20", "+")
URLNode.render = new_render
This page was useful https://github.com/django/django/blob/master/django/template/defaulttags.py
I assume by "an Existing Django Template Tag" you mean a tag in a different app.
Create a templatetags/tagfile.py
that registers a tag with the same name. Make sure that tagfile
is the same name that the template loads with {% load tagfile %}
for getting the original tag.
Also, make sure your app is listed after the original app in INSTALLED_APPS
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With