What You'll Learn in This Hour |
|
This hour covers extending the template engine to create advanced view configurations. Django provides many capabilities with its built-in tags. However, as you begin creating new custom tags and filters in your projects, a whole new world opens up.
This hour also discusses how to create custom tags and filters that you can use in your templates to reduce the amount of code necessary to generate web pages. The examples in this hour are simple to enable you to quickly understand customizing the template engine. Keep in mind that you can really do much more in your custom tags to solve problems.
The following sections discuss how to load template files from applications. They also show you how to create custom tag and filter libraries to extend Django's template system.
In Hour 7, "Implementing Django Templates to Create Custom Views," we discussed how to configure a template directory by setting TEMPLATE_DIRS in the project's settings.py file. The TEMPLATE_DIRS setting is used by the django.template.loaders.filesystem loader, which is the default loader.
Django has another template loader that is useful when organizing your templates for specific applications. The django.template.app_directories loader searches for templates in a templates subdirectory of installed applications.
For example, if you enable the app_directories loader for a site called mySite that has an application called myApp, you could store templates in the mySite/myApp/templates directory.
As a security measure, the app_directories loader searches only template directories in applications that are listed in the INSTALLED_APPS setting of the settings.py file.
To enable the app_directories loader, add the following line to the TEMPLATE_LOADERS setting of the settings.py file:
'django.template.loaders.app_directories.load_template_source',
By the Way
If you plan to distribute your applications using Python eggs, you can use the django.template.loaders.eggs.load_template_source template loader. The eggs template loader works the same as the app_directories loader, except that it loads templates from Python eggs rather than directly from the file system.