Previous Page Next Page

Extending the Template System

Django's built-in tags and filters provide enough features for most web pages. However, sometimes you will want to implement your own filters and tags.

Django makes it easy to add your own custom filters and tags to extend the template system by creating your own templatetags application.

To create a templatetags application, you create a templatetags directory as a subdirectory inside an installed application at the same level as the application's models.py file. Then you create an __init__.py file in that directory to tell Python that this is a package containing Python code.

After you have created the templatetags application, you can create custom template tag and filter libraries. To create a template tag or filter library, create a blank Python document in the templatetags directory. Then add the following lines of code at the top of the document to create a Library object so that Django knows that it is a valid tag or filter library:

from django import template
register = template.Library()

Did you Know?

Custom template tag and filter libraries need to be placed inside installed applications. They can still be accessed by templates for other applications. If you do not want the custom templates to be placed in one of your currently installed applications, you could install a new application and leave the models.py and views.py files blank and create the templatetags application in the blank application.


You can load the custom template tag and filter libraries into templates by using the load tag and specifying the library filename without the .py extension:

{% load custom_tags %}

Watch Out!

After you create a new templatetags package, you must stop and then restart the Django server so that the new package will be available.


Try It Yourself: Create a Templatetags Application to Implement Custom Tags and Filters

In this section, you will create a templatetags application in which you can create custom template tag and filter libraries.

Follow these steps to install a blank Custom application and create a templatetags package in that application:

1.
Stop the Django development server.

2.
Use the following command from the root of the iFriends project to create a new application called Custom:

python manage.py startapp Custom

3.
Create a directory in the new Custom application called iFriends/Custom/templatetags/.

4.
Copy the blank __init.py__ file from the iFriends/Custom/ directory to the iFriends/custom/templatetags/ directory to tell Python that this is an application with Python code in it.

5.
Open the iFriends/settings.py file in an editor.

6.
Add the following line of code to the INSTALLED_APPS setting file to install the Custom application:

'iFriends.Custom',

7.
Save the iFriends/settings.py file.

8.
Start the development server.


Previous Page Next Page