Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override existing Django Template Tags

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?

like image 379
tom Avatar asked Nov 04 '12 22:11

tom


2 Answers

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

like image 187
ncavig Avatar answered Sep 16 '22 11:09

ncavig


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.

like image 34
naktinis Avatar answered Sep 16 '22 11:09

naktinis