How to implement a custom template backend

Custom backends

Here’s how to implement a custom template backend in order to use another template system. A template backend is a class that inherits django.template.backends.base.BaseEngine. It must implement get_template() and optionally from_string(). Here’s an example for a fictional foobar template library:

  1. from django.template import TemplateDoesNotExist, TemplateSyntaxError
  2. from django.template.backends.base import BaseEngine
  3. from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
  4. import foobar
  5. class FooBar(BaseEngine):
  6. # Name of the subdirectory containing the templates for this engine
  7. # inside an installed application.
  8. app_dirname = 'foobar'
  9. def __init__(self, params):
  10. params = params.copy()
  11. options = params.pop('OPTIONS').copy()
  12. super().__init__(params)
  13. self.engine = foobar.Engine(**options)
  14. def from_string(self, template_code):
  15. try:
  16. return Template(self.engine.from_string(template_code))
  17. except foobar.TemplateCompilationFailed as exc:
  18. raise TemplateSyntaxError(exc.args)
  19. def get_template(self, template_name):
  20. try:
  21. return Template(self.engine.get_template(template_name))
  22. except foobar.TemplateNotFound as exc:
  23. raise TemplateDoesNotExist(exc.args, backend=self)
  24. except foobar.TemplateCompilationFailed as exc:
  25. raise TemplateSyntaxError(exc.args)
  26. class Template:
  27. def __init__(self, template):
  28. self.template = template
  29. def render(self, context=None, request=None):
  30. if context is None:
  31. context = {}
  32. if request is not None:
  33. context['request'] = request
  34. context['csrf_input'] = csrf_input_lazy(request)
  35. context['csrf_token'] = csrf_token_lazy(request)
  36. return self.template.render(context)

See DEP 182 for more information.

Debug integration for custom engines

The Django debug page has hooks to provide detailed information when a template error arises. Custom template engines can use these hooks to enhance the traceback information that appears to users. The following hooks are available:

Template postmortem

The postmortem appears when TemplateDoesNotExist is raised. It lists the template engines and loaders that were used when trying to find a given template. For example, if two Django engines are configured, the postmortem will appear like:

../../_images/postmortem.png

Custom engines can populate the postmortem by passing the backend and tried arguments when raising TemplateDoesNotExist. Backends that use the postmortem should specify an origin on the template object.

Contextual line information

If an error happens during template parsing or rendering, Django can display the line the error happened on. For example:

../../_images/template-lines.png

Custom engines can populate this information by setting a template_debug attribute on exceptions raised during parsing and rendering. This attribute is a dict with the following values:

  • 'name': The name of the template in which the exception occurred.
  • 'message': The exception message.
  • 'source_lines': The lines before, after, and including the line the exception occurred on. This is for context, so it shouldn’t contain more than 20 lines or so.
  • 'line': The line number on which the exception occurred.
  • 'before': The content on the error line before the token that raised the error.
  • 'during': The token that raised the error.
  • 'after': The content on the error line after the token that raised the error.
  • 'total': The number of lines in source_lines.
  • 'top': The line number where source_lines starts.
  • 'bottom': The line number where source_lines ends.

Given the above template error, template_debug would look like:

  1. {
  2. 'name': '/path/to/template.html',
  3. 'message': "Invalid block tag: 'syntax'",
  4. 'source_lines': [
  5. (1, 'some\n'),
  6. (2, 'lines\n'),
  7. (3, 'before\n'),
  8. (4, 'Hello {% syntax error %} {{ world }}\n'),
  9. (5, 'some\n'),
  10. (6, 'lines\n'),
  11. (7, 'after\n'),
  12. (8, ''),
  13. ],
  14. 'line': 4,
  15. 'before': 'Hello ',
  16. 'during': '{% syntax error %}',
  17. 'after': ' {{ world }}\n',
  18. 'total': 9,
  19. 'bottom': 9,
  20. 'top': 1,
  21. }

Origin API and 3rd-party integration

Django templates have an Origin object available through the template.origin attribute. This enables debug information to be displayed in the template postmortem, as well as in 3rd-party libraries, like the Django Debug Toolbar.

Custom engines can provide their own template.origin information by creating an object that specifies the following attributes:

  • 'name': The full path to the template.
  • 'template_name': The relative path to the template as passed into the template loading methods.
  • 'loader_name': An optional string identifying the function or class used to load the template, e.g. django.template.loaders.filesystem.Loader.