Debian Codegraph @

docs/howto/custom-template-backend.txt

raw
1 ==========================================
2 How to implement a custom template backend
3 ==========================================
4
5 Custom backends
6 ---------------
7
8 Here's how to implement a custom template backend in order to use another
9 template system. A template backend is a class that inherits
10 ``django.template.backends.base.BaseEngine``. It must implement
11 ``get_template()`` and optionally ``from_string()``. Here's an example for a
12 fictional ``foobar`` template library::
13
14 from django.template import TemplateDoesNotExist, TemplateSyntaxError
15 from django.template.backends.base import BaseEngine
16 from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
17
18 import foobar
19
20
21 class FooBar(BaseEngine):
22 # Name of the subdirectory containing the templates for this engine
23 # inside an installed application.
24 app_dirname = "foobar"
25
26 def __init__(self, params):
27 params = params.copy()
28 options = params.pop("OPTIONS").copy()
29 super().__init__(params)
30
31 self.engine = foobar.Engine(**options)
32
33 def from_string(self, template_code):
34 try:
35 return Template(self.engine.from_string(template_code))
36 except foobar.TemplateCompilationFailed as exc:
37 raise TemplateSyntaxError(exc.args)
38
39 def get_template(self, template_name):
40 try:
41 return Template(self.engine.get_template(template_name))
42 except foobar.TemplateNotFound as exc:
43 raise TemplateDoesNotExist(exc.args, backend=self)
44 except foobar.TemplateCompilationFailed as exc:
45 raise TemplateSyntaxError(exc.args)
46
47
48 class Template:
49 def __init__(self, template):
50 self.template = template
51
52 def render(self, context=None, request=None):
53 if context is None:
54 context = {}
55 if request is not None:
56 context["request"] = request
57 context["csrf_input"] = csrf_input_lazy(request)
58 context["csrf_token"] = csrf_token_lazy(request)
59 return self.template.render(context)
60
61 See `DEP 182`_ for more information.
62
63 .. _template-debug-integration:
64
65 Debug integration for custom engines
66 ------------------------------------
67
68 The Django debug page has hooks to provide detailed information when a template
69 error arises. Custom template engines can use these hooks to enhance the
70 traceback information that appears to users. The following hooks are available:
71
72 .. _template-postmortem:
73
74 Template postmortem
75 ~~~~~~~~~~~~~~~~~~~
76
77 The postmortem appears when :exc:`~django.template.TemplateDoesNotExist` is
78 raised. It lists the template engines and loaders that were used when trying to
79 find a given template. For example, if two Django engines are configured, the
80 postmortem will appear like:
81
82 .. image:: _images/postmortem.png
83
84 Custom engines can populate the postmortem by passing the ``backend`` and
85 ``tried`` arguments when raising :exc:`~django.template.TemplateDoesNotExist`.
86 Backends that use the postmortem :ref:`should specify an origin
87 <template-origin-api>` on the template object.
88
89 Contextual line information
90 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
91
92 If an error happens during template parsing or rendering, Django can display
93 the line the error happened on. For example:
94
95 .. image:: _images/template-lines.png
96
97 Custom engines can populate this information by setting a ``template_debug``
98 attribute on exceptions raised during parsing and rendering. This attribute is
99 a :class:`dict` with the following values:
100
101 * ``'name'``: The name of the template in which the exception occurred.
102
103 * ``'message'``: The exception message.
104
105 * ``'source_lines'``: The lines before, after, and including the line the
106 exception occurred on. This is for context, so it shouldn't contain more than
107 20 lines or so.
108
109 * ``'line'``: The line number on which the exception occurred.
110
111 * ``'before'``: The content on the error line before the token that raised the
112 error.
113
114 * ``'during'``: The token that raised the error.
115
116 * ``'after'``: The content on the error line after the token that raised the
117 error.
118
119 * ``'total'``: The number of lines in ``source_lines``.
120
121 * ``'top'``: The line number where ``source_lines`` starts.
122
123 * ``'bottom'``: The line number where ``source_lines`` ends.
124
125 Given the above template error, ``template_debug`` would look like::
126
127 {
128 "name": "/path/to/template.html",
129 "message": "Invalid block tag: 'syntax'",
130 "source_lines": [
131 (1, "some\n"),
132 (2, "lines\n"),
133 (3, "before\n"),
134 (4, "Hello {% syntax error %} {{ world }}\n"),
135 (5, "some\n"),
136 (6, "lines\n"),
137 (7, "after\n"),
138 (8, ""),
139 ],
140 "line": 4,
141 "before": "Hello ",
142 "during": "{% syntax error %}",
143 "after": " {{ world }}\n",
144 "total": 9,
145 "bottom": 9,
146 "top": 1,
147 }
148
149 .. _template-origin-api:
150
151 Origin API and 3rd-party integration
152 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
153
154 Django templates have an :class:`~django.template.base.Origin` object available
155 through the ``template.origin`` attribute. This enables debug information to be
156 displayed in the :ref:`template postmortem <template-postmortem>`, as well as
157 in 3rd-party libraries, like the :pypi:`Django Debug Toolbar
158 <django-debug-toolbar>`.
159
160 Custom engines can provide their own ``template.origin`` information by
161 creating an object that specifies the following attributes:
162
163 * ``'name'``: The full path to the template.
164
165 * ``'template_name'``: The relative path to the template as passed into the
166 template loading methods.
167
168 * ``'loader_name'``: An optional string identifying the function or class used
169 to load the template, e.g. ``django.template.loaders.filesystem.Loader``.
170
171 .. _DEP 182: https://github.com/django/deps/blob/main/final/0182-multiple-template-engines.rst