What are some popular Django template engines

1. Template engine support

As a web framework, Django needs a convenient way to generate HTML dynamically. The most common method is based on templates. The template contains the static part of the required HTML output and a special syntax that describes the dynamic content to be inserted. For examples of creating HTML pages with templates, see: Example 3

Django projects can be configured with one or more template engines (or without templates). The Django backend has a built-in template system, creatively known as the Django Template Language (DTL), which is a popular alternative to JINJA2. The backend can also use other available template languages ​​provided by third parties.

Django defines a standard API for loading and rendering templates, regardless of the backend template system. When loading, the template is searched for and preprocessed for a specific identifier. Usually the results of the compilation are stored in memory. The rendering tool inserts the context data into the template and returns the result string.

Django template language It is Django's own template system. Until Django 1.8, this was the only built-in option. This is a good template library, although it is quite rigid and has its own properties when used. Unless you have an urgent reason to choose a different backend, consider using DTL, especially if you are writing a pluggable application and planning to distribute templates. Some templates in Django's contrib apps, zdjango.contrib.admin, using DTL.

For historical reasons, the general support of the template engine and the implementation of the Django template language is in the module's namespace.


It is not safe for the template system to use untrusted template author templates. For example, a site should not allow its users to post their own templates because template authors could, for example, perform XSS attacks and gain access to template variables that contain sensitive information.

1.1 configuration

Template Engine for TEMPLATES settings Medium configuration. This is a configuration list, one for each engine. The default value is empty. Define a useful value in the settings.py file generated by the startproject command:

BACKENDEs is the virtual Python path of the template engine class that implements the Django template backend API. The built-in backend is with。

Since most engines load templates from files, the top-level configuration of each engine contains two general settings:

  • A directory listing of the template source files is defined and the search engine searches in search order.
  • Tell the engine whether to search for templates in installed applications. Each backend defines the general name of the subdirectory in the application in which its templates are to be saved.

Although not common, you can configure multiple instances of the same backend with different options. In this case you should define a unique NAME。

OPTIONS Contains backend-specific settings.

1.2 Use

The module django.template.loader defines two functions for loading templates.

(1) source code
This function loads the template with the specified name and returns a template object.

The exact type of return value depends on the backend into which the template is loaded. Each backend has its own template class.

get_template () tries each template engine in turn until it is successful. If no template is found, the template is triggered. If a template is found but it contains invalid syntax, the template is triggered。

How templates are searched for and loaded depends on the backend and the configuration of the individual engines.

If you want to limit the search to a specific template engine, pass the engine in the using parameterNAME。

(2) source
select_template () is similar to get_template (), but uses a list of template names. It tries each name in turn and returns the first existing template.

If the template fails to load, django.template can throw the following two exceptions:

(1) source
This exception is thrown when the template cannot be found. It accepts the following optional parameters to fill in on the debug page Template postmortem :

  • baking
    The template backend instance where an exception occurred.
  • tried
    A list of sources to try when looking for templates. This is formatted as a list of (origin, status) tuples, where origin is origin-likeObject and status is a string containing the reason why the template was not found.
  • chain
    is triggered when a template is loadedException list. This is used by the get_template () function which tries to load a specific template from multiple engines.

(2) source
This exception is thrown when a template is found but it contains errors.

(3) Template.render (context = None , request = None)
Render this template in the given context.

The template object returned by get_template () and select_template () must provide the render () method.

If context is provided, it must be a dictionary type. If not specified, the engine renders the template in an empty context.

When a request is made, it must be HTTPRequest. The engine must then provide it along with the CSRF token in the template. How this goal can be achieved depends on each backend.

This is an example of a search algorithm. In this example, TEMPLATES is set to:

When you call, Django will find the files in the following order:

  • /home/html/example.com/story_detail.html(‘django ’engine)
    /home/html/default/story_detail.html(‘django ’engine)
    /home/html/jinja2/story_detail.html(‘jinja2 ’engine)

When you call, this is what Django will be looking for:

  • /home/html/example.com/story_253_detail.html(‘django ’engine)
    /home/html/default/story_253_detail.html(‘django ’engine)
    /home/html/jinja2/story_253_detail.html(‘jinja2 ’engine)
    /home/html/example.com/story_detail.html(‘django ’engine)
    /home/html/default/story_detail.html(‘django ’engine)
    /home/html/jinja2/story_detail.html(‘jinja2 ’engine)

If Django finds an existing template, it will stop searching.

With select_template () you can load templates flexibly. For example, if you've written a message and want certain messages to have custom templates, use something like content. This allows you to use custom templates for individual stories and provide fallback templates for stories without custom templates. ↑

It is possible to organize templates into subdirectories in any directory that contains templates - and this is also desirable. The convention is to create a subdirectory for each Django application and add subdirectories to those subdirectories if necessary.

This is for your own reason. Storing all of the templates in the root of a single directory can get confusing.

Simply use the following forward slashes to load templates in subdirectories:

Using the same options as in the templates above, it tries to load the following template:

  • /home/html/example.com/news/story_detail.html(‘django ’engine)
    /home/html/default/news/story_detail.html(‘django ’engine)
    /home/html/jinja2/news/story_detail.html(‘jinja2 ’engine)

To reduce the repeatability of loading and rendering templates, Django also offers a link function for an automated process.

render_to_string () loads a template like get_template () and immediately calls its render () method. It requires the following parameters.

  • template_name
    The name of the loading and rendering template. If it's a list of template names, Django uses select_template () instead of get_template () to find the template.
  • context
    A dictionary is used as the rendering context for the template.
  • request
    The optional HttpRequest is available when rendering templates.
  • using
    Optional name of the template engine. The search for templates is limited to this engine.

Application examples:

You can also see the render () link function that calls render_to_string () and returns the result to HttpResponse that is suitable for returning from view.

Finally, you can use the configured engine directly:

The template engine is available at Used in:

In this example, the search word "django" is the name of the engine.