Dec 19 2008

Builtin template tags and filters in Django

Category: Django, Pythonvbmendes @ 12:11

A good feature of Django Framework is the template tags and template filters. But it sucks when you have to load the filters in each template like this:

{% load mytemplatetags %}

It was much better if you just use the filters, without the need to load it. The reason you have to load is to achieve a better performance. But there’s a function of the template module called add_to_builtins that solves this problem. You can easily define a template tag or filter as builtin and use it like the builtin django template tags and filters. Just put this code in a file that is loaded ever, like the init.py of your project.

from django.template import add_to_builtins
add_to_builtins('path.to.templatetags.file')

Where ‘path.to.templatetags.file’ is the path of the file containing the template tags. For example, I have an app, inside my project, named mytagsapp. Inside this app I have the module templatetags with a file named mytags.py with my custom tags. So I will have to call add_builtins(‘mytagsapp.templatetags.mytags’). My project folder should look like this:

Folders structure

Folders structure

Make sure your app is in the INSTALED_APPS setting in your settings.py project. It will guarantee that the init.py of you app will get called. So just put the code above in this file (red in image).

Remember to not use this feature with all your template filters as it will mean loss of performance.

Bookmark and Share

Tags: , , , ,

3 Responses to “Builtin template tags and filters in Django”

  1. 1
    paul Says:

    thank you a lot, this is all i need for last two days

  2. 2
    playfish Says:

    eventhough I squander most of my working day on the internet learning games like zynga poker or farmville, I nonetheless like to dedicate some spare time to look through a few blogs on occasion and I am content to report this most recent post is genuinely more than a little effective and substantially more desirable than 1 / 2 the other waste I read today , anyhow i’m off to enjoy a couple of rounds of facebook poker

  3. 3
    Selena Coogan Says:

    Hi, this is one awesome article! Thanks for posting this. I was hunting for a site that has this kind of info. I just love farmville! Lucky I found this one! I’ll be going in here again for sure! ;)

Leave a Reply