Debian Codegraph @

doc/content.adoc

raw
1 = django-jinja - jinja2 backend for Django
2 Andrey Antukh, <[email protected]>
3 2.11.0
4 :toc: left
5 :!numbered:
6 :source-highlighter: pygments
7 :pygments-style: friendly
8 :sectlinks:
9
10
11 == Introduction
12
13 django-jinja is a xref:license[BSD Licensed], simple and non-obstructive jinja2
14 backend for Django.
15
16
17 === Rationale
18
19 Jinja2 provides certain advantages over the native system of Django, for example,
20 explicit calls to callable from templates, has better performance and has a plugin
21 system, etc ...
22
23 Django comes with a jinja backend, why should I use *django-jinja*?
24
25 The Django builtin backend has a very limited set of features if we compare it with
26 the django template engine and in my opinion is not very usable because it does not
27 integrate well with the rest of django such as its filters, template tags and
28 preloading of templatetags, among others.
29
30 *django-jinja* comes to the rescue and adds everything missing. This is a brief
31 list of differences with django's built-in backend:
32
33 - Auto-load templatetags compatible with Jinja2 the same way as Django.
34 - Find the templates as usual in `"<appname>/templates"` directory instead
35 of `"<appname>/jinja2"` directory (you can overwrite this behavior, see below).
36 - Django templates can coexist with Jinja2 templates without any problems.
37 It works as middleware, intercepts Jinja templates by file path pattern.
38 - Django template filters and tags can mostly be used in Jinja2 templates.
39 - I18n subsystem adapted for Jinja2 (makemessages now collects messages from
40 Jinja templates, respects the `ext.i18n.trimmed` policy)
41 - jinja2 bytecode cache adapted for using django's cache subsystem.
42 - Support for django context processors.
43
44
45 [NOTE]
46 ====
47 The usage of context processors is available for compatibility and migrations,
48 but creating new context processors is not the recommended way to set global context.
49 With *django-jinja*, you can do this by setting global data or global constants. See below,
50 in the "Custom filters, globals, constants and tests" section.
51 ====
52
53
54 === Requirements
55
56 - Python >= 3.8
57 - Django >= 3.2
58 - jinja2 >= 3.0
59
60 If you are using older versions of Django or Python, you need an older version of django-jinja:
61
62 |===
63 |django-jinja |supported python versions |supported django versions
64
65 |==1.4.2
66 |2.7, 3.3, 3.4
67 |1.5, 1.6, 1.7, 1.8
68
69 |==2.4.1
70 |2.7, 3.4, 3.5
71 |1.8, 1.11
72
73 |==2.6.0
74 |3.5 (not django 3.0), 3.6, 3.7, 3.8
75 |1.11, 2.2, 3.0
76
77 |>=2.7.0
78 |3.5 (django 2.2 only), 3.6, 3.7, 3.8, 3.9
79 |2.2, 3.0, 3.1, 3.2
80
81 |>=2.8.0
82 |3.6, 3.7, 3.8, 3.9
83 |2.2, 3.0, 3.1, 3.2
84
85 |>=2.10.0
86 |3.6, 3.7, 3.8, 3.9, 3.10
87 |2.2, 3.2, 4.0
88
89 |>=2.11.0
90 |3.8, 3.9, 3.10, 3.11
91 |3.2, 4.0, 4.1, 4.2
92 |===
93
94
95 === Installation
96
97 The simplest way to install **django-jinja** is using **pip**:
98
99 [source, bash]
100 ----
101 pip install django-jinja
102 ----
103
104
105 == Quick Start
106
107 Add it to Django's installed apps list:
108
109 [source, python]
110 ----
111 INSTALLED_APPS += ('django_jinja',)
112 ----
113
114 Followed by the basic template engine configuration:
115
116 [source, python]
117 ----
118 TEMPLATES = [
119 {
120 "BACKEND": "django_jinja.jinja2.Jinja2",
121 "DIRS": [],
122 "APP_DIRS": True,
123 "OPTIONS": {}
124 },
125 {
126 "BACKEND": "django.template.backends.django.DjangoTemplates",
127 "DIRS": [],
128 "APP_DIRS": True,
129 "OPTIONS": {}
130 },
131 ]
132 ----
133
134 [NOTE]
135 ====
136 If you are using the default value for the app templates directory of the
137 django-jinja backend, take care of the template engines order, because the
138 django-jinja backend by default uses the same directory for the templates as
139 the django template engine. If you put the django engine first every jinja
140 template will be found by the django engine.
141 ====
142
143 To read more on the logic of the `DIRS` and `APP_DIRS` settings,
144 and how the engines resolve template paths, check out
145 link:https://docs.djangoproject.com/en/dev/topics/templates/#support-for-template-engines[Django's section on setting up template engines].
146
147
148 == User Guide
149
150 === Using Jinja2 templates in your views
151
152 By default, *django-jinja*'s template backend matches files with the extension `.jinja`,
153 and (if using the `APP_DIRS` template loader) it crawls the same `templates` folders
154 within your apps as the Django Template Language (DTL) engine does.
155
156 So, all you have to do to switch your template renderer is to change the file extension of the template.
157 Make sure your templates use the right engine's syntax corresponding to their file extensions!
158
159 As an example, these class-based views work for both Jinja2 and DTL in a project set up like in xref:_quick_start[Quick Start]:
160
161 [source, python]
162 ----
163 """
164 app layout:
165 myapp/
166 ├── __init__.py
167 ├── apps.py
168 ├── templates
169 │ ├── bar.html
170 │ └── foo.jinja
171 └── views.py <--(you are here)
172 """
173 from django.views.generic import TemplateView
174
175 class FooView(TemplateView):
176 template_name = 'foo.jinja' # renders with Jinja2
177
178 class BarView(TemplateView):
179 template_name = 'bar.html' # renders with DTL
180 ----
181
182 [NOTE]
183 ====
184 Jinja2 and DTL templates can't call each other with `{% extends %}` or `{% include %}`.
185 If you mix them up, django will raise `django.template.TemplateDoesNotExist` or `TemplateSyntaxError`.
186
187 If you use template inheritance in your project to keep every page looking the same,
188 you may end up needing to maintain two versions of your commonly used templates, like
189 `base.jinja` and `base.html`, that render the same, each using their own template language.
190 ====
191
192 For advice on converting from a DTL to a Jinja2 template,
193 see xref:_differences_with_django_template_engine[Differences with Django Template Engine].
194
195
196 === Advanced template pattern matching
197
198 If the above default behavior is not to your liking, you can tune it using these `OPTIONS`:
199
200 [source, python]
201 ----
202 "OPTIONS": {
203 # django-jinja defaults
204 "match_extension": ".jinja",
205 "match_regex": None,
206 "app_dirname": "templates",
207 }
208 ----
209
210 - To match only file paths that end with a certain string, use `match_extension`.
211 - To use regular expressions to match or exclude certain paths, use `match_regex`.
212 - If both are set, both tests must pass for the backend to try and render the file.
213 - If both are disabled with `None`, the backend will try and render *any* file it finds
214 (and preclude any subsequent engines in `TEMPLATES`).
215
216 This example matches `.html` files instead of `.jinja` across the entire project,
217 but uses a regular expression to exclude matching DTL templates used by the admin interface.
218
219 [source, python]
220 ----
221 "OPTIONS": {
222 # Match the template names ending in .html but not the ones in the admin folder.
223 "match_extension": ".html",
224 "match_regex": r"^(?!admin/).*",
225 }
226 ----
227
228 As said previously, when using `APP_DIRS`, django-jinja's backend uses the same
229 `templates` directory as the django template engine. To change it to use another
230 directory in your apps, you can use the `app_dirname` option:
231
232 [source, python]
233 ----
234 "OPTIONS": {
235 # Match the templates at <app>/jinja2/*.html`, leaving <app>/templates/ for DTL.
236 "match_extension": ".html",
237 "app_dirname": "jinja2",
238 }
239 ----
240
241
242 === Context processors support
243
244 It is a helper to use django's context processors with jinja2 backend
245 for django 1.8.
246
247 .Example: set up a bunch of context processors:
248 [source, python]
249 ----
250 "OPTIONS": {
251 "context_processors": [
252 "django.contrib.auth.context_processors.auth",
253 "django.template.context_processors.debug",
254 "django.template.context_processors.i18n",
255 "django.template.context_processors.media",
256 "django.template.context_processors.static",
257 "django.template.context_processors.tz",
258 "django.contrib.messages.context_processors.messages",
259 ],
260 }
261 ----
262
263 As with the django template engine, this is a default list of context processors, and you can skip
264 setting them if you do not have your own.
265 Furthermore, the purpose of django-jinja's context processor support is to help with migrations,
266 but context processors are no longer the recommended way to set global variables and functions.
267 For the recommended way, see the next section.
268
269 [NOTE]
270 ====
271 Remember that django (1.8.x and 1.9.x) is backward compatible with
272 the old template api and this has its own trade-offs. If you find yourself using functions
273 like `render_to_string` or `render_to_response` from django, do not forget to pass the
274 request parameter in order to make context processors work.
275 ====
276
277
278 === Custom filters, globals, constants and tests
279
280 This is the recommended way to set up additional jinja variables, tests, and filters, in your settings.
281
282 [source, python]
283 ----
284 "OPTIONS": {
285 "tests": {
286 "mytest": "path.to.tests.mytestfn",
287 },
288 "filters": {
289 "myfilter": "path.to.filters.myfilterfn",
290 },
291 "constants": {
292 "hello": "hello world",
293 },
294 "globals": {
295 "somefn": "path.to.functions.somefn",
296 }
297 }
298 ----
299
300
301 === Set policies
302
303 To set link:https://jinja.palletsprojects.com/en/latest/api/#policies[environment policies] introduced in Jinja2 2.9:
304
305 [source, python]
306 ----
307 "OPTIONS": {
308 "policies": {
309 "ext.i18n.trimmed": True,
310 },
311 }
312 ----
313
314
315 === Add additional extensions
316
317 django-jinja, by default sets up a great amount of extensions to make your experience
318 using jinja in django painless. But if you want to add more extensions, you can do it
319 using the `extensions` entry of the backend options:
320
321 [source, python]
322 ----
323 from django_jinja.builtins import DEFAULT_EXTENSIONS
324
325 "OPTIONS": {
326 "extensions": DEFAULT_EXTENSIONS + [
327 # Your extensions here...
328 "path.to.your.Extension"
329 ]
330 }
331
332 ----
333
334 === Setting the template engine name
335
336 Keep in mind that the automatically inferred `NAME` for any template backend
337 link:https://docs.djangoproject.com/en/dev/ref/settings/#std-setting-TEMPLATES-NAME[will depend on the backend's import path].
338 This name is used when you need to specify a template engine by name
339 (e.g. `render_to_string("myapp/template.jinja", context, using="jinja2")`).
340
341 In previous versions of django-jinja, the backend's import path was `django_jinja.backend.Jinja2`,
342 providing the unhelpful default engine name, `"backend"`.
343
344 Now, the import path `django_jinja.jinja2.Jinja2` can be used,
345 which provides a more meaningful engine name, `"jinja2"`.
346
347 The old import path is still available for compatability with existing Django projects.
348
349
350 === Gettext Style
351
352 Jinja2 implements two styles of gettext. You can read about it here:
353 https://jinja.palletsprojects.com/en/latest/extensions/#new-style-gettext
354
355 You can switch to concrete style using the `newstyle_gettext` entry on
356 backend options:
357
358 [source, python]
359 ----
360 "OPTIONS": {
361 "newstyle_gettext": True,
362 }
363 ----
364
365
366 === Complete example
367
368 This is a complete configuration example with django-jinja's defaults:
369
370 [source, python]
371 ----
372 TEMPLATES = [
373 {
374 "BACKEND": "django_jinja.jinja2.Jinja2",
375 "APP_DIRS": True,
376 "OPTIONS": {
377 "match_extension": ".jinja",
378 "match_regex": None,
379 "app_dirname": "templates",
380 # Can be set to "jinja2.Undefined" or any other subclass.
381 "undefined": None,
382 "newstyle_gettext": True,
383 "tests": {
384 # "mytest": "path.to.my.test",
385 },
386 "filters": {
387 # "myfilter": "path.to.my.filter",
388 },
389 "globals": {
390 # "myglobal": "path.to.my.globalfunc",
391 },
392 "constants": {
393 # "foo": "bar",
394 },
395 "policies": {
396 # "ext.i18n.trimmed": True,
397 },
398 "extensions": [
399 "jinja2.ext.do",
400 "jinja2.ext.loopcontrols",
401 "jinja2.ext.i18n",
402 "django_jinja.builtins.extensions.CsrfExtension",
403 "django_jinja.builtins.extensions.CacheExtension",
404 "django_jinja.builtins.extensions.DebugExtension",
405 "django_jinja.builtins.extensions.TimezoneExtension",
406 "django_jinja.builtins.extensions.UrlsExtension",
407 "django_jinja.builtins.extensions.StaticFilesExtension",
408 "django_jinja.builtins.extensions.DjangoFiltersExtension",
409 ],
410 "bytecode_cache": {
411 "name": "default",
412 "backend": "django_jinja.cache.BytecodeCache",
413 "enabled": False,
414 },
415 "autoescape": True,
416 "auto_reload": settings.DEBUG,
417 "translation_engine": "django.utils.translation",
418 }
419 },
420 ]
421 ----
422
423
424 == Differences with Django Template Engine
425
426 === Url reversing
427
428 django-jinja comes with helpers for reverse urls. Instead of using django's approach, it uses
429 a simple function called `url`.
430
431 .Reverse urls in templates
432 [source, html+jinja]
433 ----
434 {{ url('ns:name', pk=obj.pk) }}
435 ----
436
437 This approach is very flexible, because we do not need additional options to set a result
438 if executing url in one variable. With jinja2 you can use the set template tag for it:
439
440 [source, html+jinja]
441 ----
442 {% set myurl=url("ns:name", pk=obj.pk) %}
443 ----
444
445 === Static files
446
447 Like urls, static files can be resolved with the simple `static` function available globally
448 in jinja context:
449
450 .Example resolving static files
451 [source, html+jinja]
452 ----
453 {{ static("js/lib/foo.js") }}
454 ----
455
456
457 === i18n support
458
459 django-jinja inherits the jinja2 approach for handling translation strings. You can read more about
460 it here: https://jinja.palletsprojects.com/en/latest/templates/#i18n
461
462 [source, html+jinja]
463 ----
464 {{ _('Hello %(name)s', name=user.name) }}
465
466 {% trans name=user.name %}
467 Hello {{ name }}
468 {% endtrans %}
469 ----
470
471 Additionally, django-jinja extends django's `makemessages` command to make it work
472 with jinja2 i18n tags.
473
474 If you want more django-like i18n-related tags, you can use extensions from
475 https://github.com/MoritzS/jinja2-django-tags.
476
477
478 === Replace jinja filters with django versions
479
480 Django and Jinja overlap in a little subset of template filters. To properly handle this, django-jinja
481 uses the jinja versions by default. But if you want a django version of them, you should use
482 the "django_jinja.builtins.extensions.DjangoExtraFiltersExtension" extension.
483
484 The affected filters are: title, upper, lower, urlencode, urlize, wordcount, wordwrap, center
485 join, length, random, default, filesizeformat, pprint.
486
487
488 === Registering filters in a "django" way.
489
490 django-jinja comes with facilities for loading template filters, globals and tests
491 from django applications.
492
493 Here an example:
494
495 [source, python]
496 ----
497 # <someapp>/templatetags/<anyfile>.py
498 # don't forget to create __init__.py in templatetags dir
499
500 from django_jinja import library
501 import jinja2
502
503 @library.test(name="one")
504 def is_one(n):
505 """
506 Usage: {% if m is one %}Foo{% endif %}
507 """
508 return n == 1
509
510 @library.filter
511 def mylower(name):
512 """
513 Usage: {{ 'Hello'|mylower() }}
514 """
515 return name.lower()
516
517 @library.filter
518 @jinja2.pass_context
519 def replace(context, value, x, y):
520 """
521 Filter with template context. Usage: {{ 'Hello'|replace('H','M') }}
522 """
523 return value.replace(x, y)
524
525
526 @library.global_function
527 def myecho(data):
528 """
529 Usage: {{ myecho('foo') }}
530 """
531 return data
532
533
534 @library.global_function
535 @library.render_with("test-render-with.jinja")
536 def myrenderwith(*args, **kwargs):
537 """
538 Render result with jinja template. Usage: {{ myrenderwith() }}
539 """
540 return {"name": "Foo"}
541
542
543 from .myextensions import MyExtension
544 library.extension(MyExtension)
545 ----
546
547 This only works within a Django app. If you don't have an app for your project, create an app specifically for this purpose and put your templatetags there.
548
549 === Render 4xx/500 pages with jinja
550
551 django-jinja also provides a set of views for easy
552 render 4xx/500 pages using jinja engine:
553
554 [source, python]
555 ----
556 # yourproject/urls.py
557 from django_jinja import views
558
559 handler400 = views.BadRequest.as_view()
560 handler403 = views.PermissionDenied.as_view()
561 handler404 = views.PageNotFound.as_view()
562 handler500 = views.ServerError.as_view()
563 ----
564
565
566 == Known Issues
567
568 - The above handler500 is broken as of django 2.2. see: https:github.com/niwinz/django-jinja/issues/234
569
570
571
572 == Builtin contrib modules
573
574 *django-jinja* comes with some additional contrib modules that adapt a limited set of external
575 django apps for easy use from jinja templates. Please note that in order to use any of these
576 contrib modules, you'll need to install the relevant dependent packages yourself first.
577
578
579 [NOTE]
580 ====
581 In django, creating new tags is simpler than in Jinja2. You should remember that
582 in jinja tags are really extensions and have a different purpose than the django template tags.
583
584 Thus for many things that the django template system uses tags, django-jinja will provide
585 functions with the same functionality.
586 ====
587
588
589 easy-thumbnails
590 ~~~~~~~~~~~~~~~
591
592 Easy Thumbnails is a thumbnail generation library for Django.
593
594 .Activate plugin (settings.py)
595 [source, python]
596 ----
597 INSTALLED_APPS += ('django_jinja.contrib._easy_thumbnails',)
598 ----
599
600 .Usage
601 [source, html+jinja]
602 ----
603 {{ thumbnail(file, size=(400, 400)) }}
604 {{ user.avatar|thumbnail_url("alias") }}
605 ----
606
607 django-subdomains
608 ~~~~~~~~~~~~~~~~~
609
610 Subdomain helpers for the Django framework, including subdomain-based URL routing.
611
612 .Activate plugin (settings.py)
613 [source, python]
614 ----
615 INSTALLED_APPS += ('django_jinja.contrib._subdomains',)
616 ----
617
618 .Usage
619 [source, html+jinja]
620 ----
621 {{ url('homepage', subdomain='wildcard') }}
622 ----
623
624
625 humanize
626 ~~~~~~~~
627
628 Django comes with the humanize library that exposes some useful template filters.
629
630 .Activate plugin (settings.py)
631 [source, python]
632 ----
633 INSTALLED_APPS += ('django_jinja.contrib._humanize',)
634 ----
635
636 link:https://docs.djangoproject.com/en/dev/ref/contrib/humanize/[Complete list of available filters]
637
638
639 .[[license]]
640 License
641 -------
642
643 [source,text]
644 ----
645 Copyright (c) 2011-2017 Andre Antukh <[email protected]>
646
647 All rights reserved.
648
649 Redistribution and use in source and binary forms, with or without
650 modification, are permitted provided that the following conditions
651 are met:
652 1. Redistributions of source code must retain the above copyright
653 notice, this list of conditions and the following disclaimer.
654 2. Redistributions in binary form must reproduce the above copyright
655 notice, this list of conditions and the following disclaimer in the
656 documentation and/or other materials provided with the distribution.
657 3. The name of the author may not be used to endorse or promote products
658 derived from this software without specific prior written permission.
659
660 THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
661 IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
662 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
663 IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
664 INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
665 NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
666 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
667 THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
668 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
669 THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
670 ----