How to implement a custom template backend

    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:

    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:

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

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

    • '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.
    • '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. (8, ''),
    12. ],
    13. 'line': 4,
    14. 'before': 'Hello ',
    15. 'during': '{% syntax error %}',
    16. 'after': ' {{ world }}\n',
    17. 'total': 9,
    18. 'bottom': 9,
    19. 'top': 1,
    20. }

    Django templates have an 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 .

    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.