Debian Codegraph @

docs/usage/templating.rst

raw
1 Templating
2 ==========
3
4 Litestar has built-in support for `Jinja2 <https://jinja.palletsprojects.com/en/3.0.x/>`_
5 , `Mako <https://www.makotemplates.org/>`_ and `Minijinja <https://github.com/mitsuhiko/minijinja/tree/main/minijinja-py>`_
6 template engines, as well as abstractions to make use of any template engine you wish.
7
8 Template engines
9 ----------------
10
11 To stay lightweight, a Litestar installation does not include the *Jinja*, *Mako* or *Minijinja*
12 libraries themselves. Before you can start using them, you have to install it via the
13 respective extra:
14
15 .. tab-set::
16
17 .. tab-item:: Jinja
18 :sync: jinja
19
20 .. code-block:: shell
21
22 pip install 'litestar[jinja]'
23
24 .. tab-item:: Mako
25 :sync: mako
26
27 .. code-block:: shell
28
29 pip install 'litestar[mako]'
30
31 .. tab-item:: MiniJinja
32 :sync: minijinja
33
34 .. code-block:: shell
35
36 pip install 'litestar[minijinja]'
37
38 .. tip::
39
40 *Jinja* is included in the ``standard`` extra. If you installed Litestar using
41 ``litestar[standard]``, you do not need to explicitly add the ``jinja`` extra.
42
43
44 Registering a template engine
45 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
46
47 To register one of the built-in template engines you simply need to pass it to the Litestar constructor:
48
49 .. tab-set::
50
51 .. tab-item:: Jinja
52 :sync: jinja
53
54 .. literalinclude:: /examples/templating/template_engine_jinja.py
55 :language: python
56
57 .. tab-item:: Mako
58 :sync: mako
59
60 .. literalinclude:: /examples/templating/template_engine_mako.py
61 :language: python
62
63 .. tab-item:: MiniJinja
64 :sync: minijinja
65
66 .. literalinclude:: /examples/templating/template_engine_minijinja.py
67 :language: python
68
69 .. note::
70
71 The ``directory`` parameter passed to :class:`TemplateConfig <litestar.template.TemplateConfig>`
72 can be either a directory or list of directories to use for loading templates.
73
74 Registering a Custom Template Engine
75 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
76
77 The above example will create a jinja Environment instance, but you can also pass in your own instance.
78
79 .. code-block:: python
80
81
82 from litestar import Litestar
83 from litestar.contrib.jinja import JinjaTemplateEngine
84 from litestar.template import TemplateConfig
85 from jinja2 import Environment, DictLoader
86
87 my_custom_env = Environment(loader=DictLoader({"index.html": "Hello {{name}}!"}))
88 app = Litestar(
89 template_config=TemplateConfig(
90 instance=JinjaTemplateEngine.from_environment(my_custom_env)
91 )
92 )
93
94 .. note::
95
96 The ``instance`` parameter passed to :class:`TemplateConfig <litestar.template.TemplateConfig>`
97 can not be used in conjunction with the ``directory`` parameter, if you choose to use instance you're fully responsible on the engine creation.
98
99 Defining a custom template engine
100 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
101
102 If you wish to use another templating engine, you can easily do so by implementing
103 :class:`TemplateEngineProtocol <litestar.template.TemplateEngineProtocol>`. This class accepts a generic
104 argument which should be the template class, and it specifies two methods:
105
106 .. code-block:: python
107
108 from typing import Protocol, Union, List
109 from pydantic import DirectoryPath
110
111 # the template class of the respective library
112 from some_lib import SomeTemplate
113
114
115 class TemplateEngineProtocol(Protocol[SomeTemplate]):
116 def __init__(self, directory: Union[DirectoryPath, List[DirectoryPath]]) -> None:
117 """Builds a template engine."""
118 ...
119
120 def get_template(self, template_name: str) -> SomeTemplate:
121 """Loads the template with template_name and returns it."""
122 ...
123
124 Once you have your custom engine you can register it as you would the built-in engines.
125
126 Accessing the template engine instance
127 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
128
129 If you need to access the template engine instance, you can do so via the
130 :class:`TemplateConfig.engine <litestar.template.TemplateConfig>` attribute:
131
132 .. tab-set::
133
134 .. tab-item:: Jinja
135 :sync: jinja
136
137 .. literalinclude:: /examples/templating/engine_instance_jinja.py
138 :language: python
139
140 .. tab-item:: Mako
141 :sync: mako
142
143 .. literalinclude:: /examples/templating/engine_instance_mako.py
144 :language: python
145
146 .. tab-item:: MiniJinja
147 :sync: minijinja
148
149 .. literalinclude:: /examples/templating/engine_instance_minijinja.py
150 :language: python
151
152 Template responses
153 ------------------
154
155 Once you have a template engine registered you can return :class:`templates responses <.response.Template>` from
156 your route handlers:
157
158 .. tab-set::
159
160 .. tab-item:: Jinja
161 :sync: jinja
162
163 .. literalinclude:: /examples/templating/returning_templates_jinja.py
164 :language: python
165
166 .. tab-item:: Mako
167 :sync: mako
168
169 .. literalinclude:: /examples/templating/returning_templates_mako.py
170 :language: python
171
172 .. tab-item:: MiniJinja
173 :sync: minijinja
174
175 .. literalinclude:: /examples/templating/returning_templates_minijinja.py
176 :language: python
177
178 * ``name`` is the name of the template file within on of the specified directories. If
179 no file with that name is found, a :class:`TemplateNotFoundException <.exceptions.TemplateNotFoundException>`
180 exception will be raised.
181 * ``context`` is a dictionary containing arbitrary data that will be passed to the template
182 engine's ``render`` method. For Jinja and Mako, this data will be available in the `template context <#template-context>`_
183
184 Template Files vs. Strings
185 --------------------------
186
187 When you define a template response, you can either pass a template file name or a string
188 containing the template. The latter is useful if you want to define the template inline
189 for small templates or :doc:`HTMX </usage/htmx>` responses for example.
190
191 .. tab-set::
192
193 .. tab-item:: File name
194
195 .. code-block:: python
196 :caption: Template via file
197
198 @get()
199 async def example() -> Template:
200 return Template(template_name="test.html", context={"hello": "world"})
201
202 .. tab-item:: String
203
204 .. code-block:: python
205 :caption: Template via string
206
207 @get()
208 async def example() -> Template:
209 template_string = "{{ hello }}"
210 return Template(template_str=template_string, context={"hello": "world"})
211
212 Template context
213 ----------------
214
215 Both `Jinja2 <https://jinja.palletsprojects.com/en/3.0.x/>`_ and `Mako <https://www.makotemplates.org/>`_ support passing a context
216 object to the template as well as defining callables that will be available inside the template.
217
218 Accessing the request instance
219 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
220
221 The current :class:`Request <litestar.connection.request.Request>` is available within the
222 template context under ``request``, which also provides access to the :doc:`app instance </usage/applications>`.
223
224 Accessing ``app.state.key`` for example would look like this:
225 <strong>check_context_key: </strong>{{ check_context_key() }}
226
227 .. tab-set::
228
229 .. tab-item:: Jinja
230 :sync: jinja
231
232 .. code-block:: html
233
234 <html>
235 <body>
236 <div>
237 <span>My state value: {{request.app.state.some_key}}</span>
238 </div>
239 </body>
240 </html>
241
242
243 .. tab-item:: Mako
244 :sync: mako
245
246 .. code-block:: html
247
248 html
249 <html>
250 <body>
251 <div>
252 <span>My state value: ${request.app.state.some_key}</span>
253 </div>
254 </body>
255 </html>
256
257
258 .. tab-item:: MiniJinja
259 :sync: minijinja
260
261 .. code-block:: html
262
263 <html>
264 <body>
265 <div>
266 <span>My state value: {{request.app.state.some_key}}</span>
267 </div>
268 </body>
269 </html>
270
271
272 Adding CSRF inputs
273 ^^^^^^^^^^^^^^^^^^
274
275 If you want to add a hidden ``<input>`` tag containing a
276 `CSRF token <https://developer.mozilla.org/en-US/docs/Web/Security/Types_of_attacks#cross-site_request_forgery_csrf>`_,
277 you first need to configure :ref:`CSRF protection <usage/middleware/builtin-middleware:csrf>`.
278 With that in place, you can now insert the CSRF input field inside an HTML form:
279
280 .. tab-set::
281
282 .. tab-item:: Jinja
283 :sync: jinja
284
285 .. code-block:: html
286
287 <html>
288 <body>
289 <div>
290 <form action="https://myserverurl.com/some-endpoint" method="post">
291 {{ csrf_input | safe }}
292 <label for="fname">First name:</label><br>
293 <input type="text" id="fname" name="fname">
294 <label for="lname">Last name:</label><br>
295 <input type="text" id="lname" name="lname">
296 </form>
297 </div>
298 </body>
299 </html>
300
301 .. tab-item:: Mako
302 :sync: mako
303
304 .. code-block:: html
305
306 <html>
307 <body>
308 <div>
309 <form action="https://myserverurl.com/some-endpoint" method="post">
310 ${csrf_input | n}
311 <label for="fname">First name:</label><br>
312 <input type="text" id="fname" name="fname">
313 <label for="lname">Last name:</label><br>
314 <input type="text" id="lname" name="lname">
315 </form>
316 </div>
317 </body>
318 </html>
319
320 .. tab-item:: MiniJinja
321 :sync: minijinja
322
323 .. code-block:: html
324
325 <html>
326 <body>
327 <div>
328 <form action="https://myserverurl.com/some-endpoint" method="post">
329 {{ csrf_input | safe}}
330 <label for="fname">First name:</label><br>
331 <input type="text" id="fname" name="fname">
332 <label for="lname">Last name:</label><br>
333 <input type="text" id="lname" name="lname">
334 </form>
335 </div>
336 </body>
337 </html>
338
339
340 The input holds a CSRF token as its value and is hidden so users cannot see or interact with it. The token is sent
341 back to the server when the form is submitted, and is checked by the CSRF middleware.
342
343 .. note::
344
345 The `csrf_input` must be marked as safe in order to ensure that it does not get escaped.
346
347 Passing template context
348 ^^^^^^^^^^^^^^^^^^^^^^^^
349
350 Passing context to the template is very simple - its one of the kwargs expected by the :class:`Template <litestar.response.Template>`
351 container, so simply pass a string keyed dictionary of values:
352
353 .. code-block:: python
354
355 from litestar import get
356 from litestar.response import Template
357
358
359 @get(path="/info")
360 def info() -> Template:
361 return Template(template_name="info.html", context={"numbers": "1234567890"})
362
363
364 Template callables
365 ------------------
366
367 Both `Jinja2 <https://jinja.palletsprojects.com/en/3.0.x/>`_ and `Mako <https://www.makotemplates.org/>`_ allow users to define custom
368 callables that are ran inside the template. Litestar builds on this and offers some functions out of the box.
369
370 Built-in callables
371 ^^^^^^^^^^^^^^^^^^
372
373 ``url_for``
374 To access urls for route handlers, you can use the ``url_for`` function. Its signature and behaviour
375 match those of :meth:`route_reverse <litestar.app.Litestar.route_reverse>`. More details about route handler indexing
376 can be found :ref:`here <usage/routing/handlers:route handler indexing>`.
377
378 ``csrf_token``
379 This function returns the request's unique :ref:`CSRF token <usage/middleware/builtin-middleware:csrf>` You can use this
380 if you wish to insert the ``csrf_token`` into non-HTML based templates, or insert it into HTML templates not using a hidden input field but
381 by some other means, for example inside a special ``<meta>`` tag.
382
383 ``url_for_static_asset``
384 URLs for static files can be created using the ``url_for_static_asset`` function. It's signature and behaviour are identical to
385 :meth:`app.url_for_static_asset <litestar.app.Litestar.url_for_static_asset>`.
386
387
388 Registering template callables
389 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
390
391 The :class:`TemplateEngineProtocol <litestar.template.base.TemplateEngineProtocol>` specifies the method
392 ``register_template_callable`` that allows defining a custom callable on a template engine. This method is implemented
393 for the two built in engines, and it can be used to register callables that will be injected into the template. The callable
394 should expect one argument - the context dictionary. It can be any callable - a function, method, or class that defines
395 the call method. For example:
396
397 .. tab-set::
398
399 .. tab-item:: Jinja
400 :sync: jinja
401
402 .. literalinclude:: /examples/templating/template_functions_jinja.py
403 :caption: ``template_functions.py``
404 :language: python
405
406 .. literalinclude:: /examples/templating/templates/index.html.jinja2
407 :language: html
408 :caption: ``templates/index.html.jinja2``
409
410 .. tab-item:: Mako
411 :sync: mako
412
413 .. literalinclude:: /examples/templating/template_functions_mako.py
414 :caption: ``template_functions.py``
415 :language: python
416
417 .. literalinclude:: /examples/templating/templates/index.html.mako
418 :language: html
419 :caption: ``templates/index.html.mako``
420
421 .. tab-item:: Minijinja
422 :sync: minijinja
423
424 .. literalinclude:: /examples/templating/template_functions_minijinja.py
425 :caption: ``template_functions.py``
426 :language: python
427
428 .. literalinclude:: /examples/templating/templates/index.html.minijinja
429 :language: html
430 :caption: ``templates/index.html.minijinja``
431
432 Run the example with ``uvicorn template_functions:app`` , visit http://127.0.0.1:8000, and
433 you'll see
434
435 .. image:: /images/examples/template_engine_callable.png
436 :alt: Template engine callable example