(c)tupeHo

Post date: Feb 11, 2009 2:46:16 PM

"Builtin template tags and filters in Django

Category: Django, Python — vbmendes @ 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:

view sourceprint?

1.{% 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.

view sourceprint?

1.from django.template import add_to_builtins

2.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

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.

Tags: builtins, Django, Python, template filters, template tags

from here