Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load a Django template tag library for all views by default

I have a small typography related templatetag library that I use on almost every page. Right now I need to load it for each template using

{% load nbsp %} 

Is there a way to load it "globally" for all views and templates at once? Putting the load tag into a base template doesn't work.

like image 590
Tomas Andrle Avatar asked Jul 26 '09 16:07

Tomas Andrle


People also ask

How do I import a Django template?

To configure the Django template system, go to the settings.py file and update the DIRS to the path of the templates folder. Generally, the templates folder is created and kept in the sample directory where manage.py lives. This templates folder contains all the templates you will create in different Django Apps.

What is Django template tags?

Django Code The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client. template.html : <ul> {% for x in mymembers %} <li>{{ x. firstname }}</li> {% endfor %} </ul> Run Example »


2 Answers

There is an add_to_builtins method in django.template.loader. Just pass it the name of your templatetags module (as a string).

from django.template.loader import add_to_builtins  add_to_builtins('myapp.templatetags.mytagslib') 

Now mytagslib is available automatically in any template.

like image 174
Daniel Roseman Avatar answered Sep 25 '22 02:09

Daniel Roseman


It will change with Django 1.9 release.

Since 1.9, correct approach will be configuring template tags and filters under builtins key of OPTIONS - see the example below:

TEMPLATES = [     {         'BACKEND': 'django.template.backends.django.DjangoTemplates',         'DIRS': [],         'APP_DIRS': True,         'OPTIONS': {             'builtins': ['myapp.builtins'],         },     }, ] 

Details: https://docs.djangoproject.com/en/dev/releases/1.9/#django-template-base-add-to-builtins-is-removed

like image 26
pbajsarowicz Avatar answered Sep 22 '22 02:09

pbajsarowicz