Debian Codegraph @

docs/howto/custom-template-tags.txt

raw
1 ==============================================
2 How to create custom template tags and filters
3 ==============================================
4
5 Django's template language comes with a wide variety of :doc:`built-in
6 tags and filters </ref/templates/builtins>` designed to address the
7 presentation logic needs of your application. Nevertheless, you may
8 find yourself needing functionality that is not covered by the core
9 set of template primitives. You can extend the template engine by
10 defining custom tags and filters using Python, and then make them
11 available to your templates using the :ttag:`{% load %}<load>` tag.
12
13 Code layout
14 ===========
15
16 The most common place to specify custom template tags and filters is inside
17 a Django app. If they relate to an existing app, it makes sense to bundle them
18 there; otherwise, they can be added to a new app. When a Django app is added
19 to :setting:`INSTALLED_APPS`, any tags it defines in the conventional location
20 described below are automatically made available to load within templates.
21
22 The app should contain a ``templatetags`` directory, at the same level as
23 ``models.py``, ``views.py``, etc. If this doesn't already exist, create it -
24 don't forget the ``__init__.py`` file to ensure the directory is treated as a
25 Python package.
26
27 .. admonition:: Development server won't automatically restart
28
29 After adding the ``templatetags`` module, you will need to restart your
30 server before you can use the tags or filters in templates.
31
32 Your custom tags and filters will live in a module inside the ``templatetags``
33 directory. The name of the module file is the name you'll use to load the tags
34 later, so be careful to pick a name that won't clash with custom tags and
35 filters in another app.
36
37 For example, if your custom tags/filters are in a file called
38 ``poll_extras.py``, your app layout might look like this:
39
40 .. code-block:: text
41
42 polls/
43 __init__.py
44 models.py
45 templatetags/
46 __init__.py
47 poll_extras.py
48 views.py
49
50 And in your template you would use the following:
51
52 .. code-block:: html+django
53
54 {% load poll_extras %}
55
56 The app that contains the custom tags must be in :setting:`INSTALLED_APPS` in
57 order for the :ttag:`{% load %}<load>` tag to work. This is a security feature:
58 It allows you to host Python code for many template libraries on a single host
59 machine without enabling access to all of them for every Django installation.
60
61 There's no limit on how many modules you put in the ``templatetags`` package.
62 Just keep in mind that a :ttag:`{% load %}<load>` statement will load
63 tags/filters for the given Python module name, not the name of the app.
64
65 To be a valid tag library, the module must contain a module-level variable
66 named ``register`` that is a ``template.Library`` instance, in which all the
67 tags and filters are registered. So, near the top of your module, put the
68 following::
69
70 from django import template
71
72 register = template.Library()
73
74 Alternatively, template tag modules can be registered through the
75 ``'libraries'`` argument to
76 :class:`~django.template.backends.django.DjangoTemplates`. This is useful if
77 you want to use a different label from the template tag module name when
78 loading template tags. It also enables you to register tags without installing
79 an application.
80
81 .. admonition:: Behind the scenes
82
83 For a ton of examples, read the source code for Django's default filters
84 and tags. They're in :source:`django/template/defaultfilters.py` and
85 :source:`django/template/defaulttags.py`, respectively.
86
87 For more information on the :ttag:`load` tag, read its documentation.
88
89 .. _howto-writing-custom-template-filters:
90
91 Writing custom template filters
92 ===============================
93
94 Custom filters are Python functions that take one or two arguments:
95
96 * The value of the variable (input) -- not necessarily a string.
97 * The value of the argument -- this can have a default value, or be left
98 out altogether.
99
100 For example, in the filter ``{{ var|foo:"bar" }}``, the filter ``foo`` would be
101 passed the variable ``var`` and the argument ``"bar"``.
102
103 Since the template language doesn't provide exception handling, any exception
104 raised from a template filter will be exposed as a server error. Thus, filter
105 functions should avoid raising exceptions if there is a reasonable fallback
106 value to return. In case of input that represents a clear bug in a template,
107 raising an exception may still be better than silent failure which hides the
108 bug.
109
110 Here's an example filter definition::
111
112 def cut(value, arg):
113 """Removes all values of arg from the given string"""
114 return value.replace(arg, "")
115
116 And here's an example of how that filter would be used:
117
118 .. code-block:: html+django
119
120 {{ somevariable|cut:"0" }}
121
122 Most filters don't take arguments. In this case, leave the argument out of your
123 function::
124
125 def lower(value): # Only one argument.
126 """Converts a string into all lowercase"""
127 return value.lower()
128
129 Registering custom filters
130 --------------------------
131
132 .. method:: django.template.Library.filter()
133
134 Once you've written your filter definition, you need to register it with
135 your ``Library`` instance, to make it available to Django's template language::
136
137 register.filter("cut", cut)
138 register.filter("lower", lower)
139
140 The ``Library.filter()`` method takes two arguments:
141
142 1. The name of the filter -- a string.
143 2. The compilation function -- a Python function (not the name of the
144 function as a string).
145
146 You can use ``register.filter()`` as a decorator instead::
147
148 @register.filter(name="cut")
149 def cut(value, arg):
150 return value.replace(arg, "")
151
152
153 @register.filter
154 def lower(value):
155 return value.lower()
156
157 If you leave off the ``name`` argument, as in the second example above, Django
158 will use the function's name as the filter name.
159
160 Finally, ``register.filter()`` also accepts three keyword arguments,
161 ``is_safe``, ``needs_autoescape``, and ``expects_localtime``. These arguments
162 are described in :ref:`filters and auto-escaping <filters-auto-escaping>` and
163 :ref:`filters and time zones <filters-timezones>` below.
164
165 Template filters that expect strings
166 ------------------------------------
167
168 .. method:: django.template.defaultfilters.stringfilter()
169
170 If you're writing a template filter that only expects a string as the first
171 argument, you should use the decorator ``stringfilter``. This will
172 convert an object to its string value before being passed to your function::
173
174 from django import template
175 from django.template.defaultfilters import stringfilter
176
177 register = template.Library()
178
179
180 @register.filter
181 @stringfilter
182 def lower(value):
183 return value.lower()
184
185 This way, you'll be able to pass, say, an integer to this filter, and it
186 won't cause an ``AttributeError`` (because integers don't have ``lower()``
187 methods).
188
189 .. _filters-auto-escaping:
190
191 Filters and auto-escaping
192 -------------------------
193
194 When writing a custom filter, give some thought to how the filter will interact
195 with Django's auto-escaping behavior. Note that two types of strings can be
196 passed around inside the template code:
197
198 * **Raw strings** are the native Python strings. On output, they're escaped if
199 auto-escaping is in effect and presented unchanged, otherwise.
200
201 * **Safe strings** are strings that have been marked safe from further
202 escaping at output time. Any necessary escaping has already been done.
203 They're commonly used for output that contains raw HTML that is intended
204 to be interpreted as-is on the client side.
205
206 Internally, these strings are of type
207 :class:`~django.utils.safestring.SafeString`. You can test for them
208 using code like::
209
210 from django.utils.safestring import SafeString
211
212 if isinstance(value, SafeString):
213 # Do something with the "safe" string.
214 ...
215
216 Template filter code falls into one of two situations:
217
218 1. Your filter does not introduce any HTML-unsafe characters (``<``, ``>``,
219 ``'``, ``"`` or ``&``) into the result that were not already present. In
220 this case, you can let Django take care of all the auto-escaping
221 handling for you. All you need to do is set the ``is_safe`` flag to ``True``
222 when you register your filter function, like so::
223
224 @register.filter(is_safe=True)
225 def myfilter(value):
226 return value
227
228 This flag tells Django that if a "safe" string is passed into your
229 filter, the result will still be "safe" and if a non-safe string is
230 passed in, Django will automatically escape it, if necessary.
231
232 You can think of this as meaning "this filter is safe -- it doesn't
233 introduce any possibility of unsafe HTML."
234
235 The reason ``is_safe`` is necessary is because there are plenty of
236 normal string operations that will turn a ``SafeData`` object back into
237 a normal ``str`` object and, rather than try to catch them all, which would
238 be very difficult, Django repairs the damage after the filter has completed.
239
240 For example, suppose you have a filter that adds the string ``xx`` to
241 the end of any input. Since this introduces no dangerous HTML characters
242 to the result (aside from any that were already present), you should
243 mark your filter with ``is_safe``::
244
245 @register.filter(is_safe=True)
246 def add_xx(value):
247 return "%sxx" % value
248
249 When this filter is used in a template where auto-escaping is enabled,
250 Django will escape the output whenever the input is not already marked
251 as "safe".
252
253 By default, ``is_safe`` is ``False``, and you can omit it from any filters
254 where it isn't required.
255
256 Be careful when deciding if your filter really does leave safe strings
257 as safe. If you're *removing* characters, you might inadvertently leave
258 unbalanced HTML tags or entities in the result. For example, removing a
259 ``>`` from the input might turn ``<a>`` into ``<a``, which would need to
260 be escaped on output to avoid causing problems. Similarly, removing a
261 semicolon (``;``) can turn ``&amp;`` into ``&amp``, which is no longer a
262 valid entity and thus needs further escaping. Most cases won't be nearly
263 this tricky, but keep an eye out for any problems like that when
264 reviewing your code.
265
266 Marking a filter ``is_safe`` will coerce the filter's return value to
267 a string. If your filter should return a boolean or other non-string
268 value, marking it ``is_safe`` will probably have unintended
269 consequences (such as converting a boolean False to the string
270 'False').
271
272 2. Alternatively, your filter code can manually take care of any necessary
273 escaping. This is necessary when you're introducing new HTML markup into
274 the result. You want to mark the output as safe from further
275 escaping so that your HTML markup isn't escaped further, so you'll need
276 to handle the input yourself.
277
278 To mark the output as a safe string, use
279 :func:`django.utils.safestring.mark_safe`.
280
281 Be careful, though. You need to do more than just mark the output as
282 safe. You need to ensure it really *is* safe, and what you do depends on
283 whether auto-escaping is in effect. The idea is to write filters that
284 can operate in templates where auto-escaping is either on or off in
285 order to make things easier for your template authors.
286
287 In order for your filter to know the current auto-escaping state, set the
288 ``needs_autoescape`` flag to ``True`` when you register your filter function.
289 (If you don't specify this flag, it defaults to ``False``). This flag tells
290 Django that your filter function wants to be passed an extra keyword
291 argument, called ``autoescape``, that is ``True`` if auto-escaping is in
292 effect and ``False`` otherwise. It is recommended to set the default of the
293 ``autoescape`` parameter to ``True``, so that if you call the function
294 from Python code it will have escaping enabled by default.
295
296 For example, let's write a filter that emphasizes the first character of
297 a string::
298
299 from django import template
300 from django.utils.html import conditional_escape
301 from django.utils.safestring import mark_safe
302
303 register = template.Library()
304
305
306 @register.filter(needs_autoescape=True)
307 def initial_letter_filter(text, autoescape=True):
308 first, other = text[0], text[1:]
309 if autoescape:
310 esc = conditional_escape
311 else:
312 esc = lambda x: x
313 result = "<strong>%s</strong>%s" % (esc(first), esc(other))
314 return mark_safe(result)
315
316 The ``needs_autoescape`` flag and the ``autoescape`` keyword argument mean
317 that our function will know whether automatic escaping is in effect when the
318 filter is called. We use ``autoescape`` to decide whether the input data
319 needs to be passed through ``django.utils.html.conditional_escape`` or not.
320 (In the latter case, we use the identity function as the "escape" function.)
321 The ``conditional_escape()`` function is like ``escape()`` except it only
322 escapes input that is **not** a ``SafeData`` instance. If a ``SafeData``
323 instance is passed to ``conditional_escape()``, the data is returned
324 unchanged.
325
326 Finally, in the above example, we remember to mark the result as safe
327 so that our HTML is inserted directly into the template without further
328 escaping.
329
330 There's no need to worry about the ``is_safe`` flag in this case
331 (although including it wouldn't hurt anything). Whenever you manually
332 handle the auto-escaping issues and return a safe string, the
333 ``is_safe`` flag won't change anything either way.
334
335 .. warning:: Avoiding XSS vulnerabilities when reusing built-in filters
336
337 Django's built-in filters have ``autoescape=True`` by default in order to
338 get the proper autoescaping behavior and avoid a cross-site script
339 vulnerability.
340
341 In older versions of Django, be careful when reusing Django's built-in
342 filters as ``autoescape`` defaults to ``None``. You'll need to pass
343 ``autoescape=True`` to get autoescaping.
344
345 For example, if you wanted to write a custom filter called
346 ``urlize_and_linebreaks`` that combined the :tfilter:`urlize` and
347 :tfilter:`linebreaksbr` filters, the filter would look like::
348
349 from django.template.defaultfilters import linebreaksbr, urlize
350
351
352 @register.filter(needs_autoescape=True)
353 def urlize_and_linebreaks(text, autoescape=True):
354 return linebreaksbr(urlize(text, autoescape=autoescape), autoescape=autoescape)
355
356 Then:
357
358 .. code-block:: html+django
359
360 {{ comment|urlize_and_linebreaks }}
361
362 would be equivalent to:
363
364 .. code-block:: html+django
365
366 {{ comment|urlize|linebreaksbr }}
367
368 .. _filters-timezones:
369
370 Filters and time zones
371 ----------------------
372
373 If you write a custom filter that operates on :class:`~datetime.datetime`
374 objects, you'll usually register it with the ``expects_localtime`` flag set to
375 ``True``::
376
377 @register.filter(expects_localtime=True)
378 def businesshours(value):
379 try:
380 return 9 <= value.hour < 17
381 except AttributeError:
382 return ""
383
384 When this flag is set, if the first argument to your filter is a time zone
385 aware datetime, Django will convert it to the current time zone before passing
386 it to your filter when appropriate, according to :ref:`rules for time zones
387 conversions in templates <time-zones-in-templates>`.
388
389 .. _howto-writing-custom-template-tags:
390
391 Writing custom template tags
392 ============================
393
394 Tags are more complex than filters, because tags can do anything. Django
395 provides a number of shortcuts that make writing most types of tags easier.
396 First we'll explore those shortcuts, then explain how to write a tag from
397 scratch for those cases when the shortcuts aren't powerful enough.
398
399 .. _howto-custom-template-tags-simple-tags:
400
401 Simple tags
402 -----------
403
404 .. method:: django.template.Library.simple_tag()
405
406 Many template tags take a number of arguments -- strings or template variables
407 -- and return a result after doing some processing based solely on
408 the input arguments and some external information. For example, a
409 ``current_time`` tag might accept a format string and return the time as a
410 string formatted accordingly.
411
412 To ease the creation of these types of tags, Django provides a helper function,
413 ``simple_tag``. This function, which is a method of
414 ``django.template.Library``, takes a function that accepts any number of
415 arguments, wraps it in a ``render`` function and the other necessary bits
416 mentioned above and registers it with the template system.
417
418 Our ``current_time`` function could thus be written like this::
419
420 import datetime
421 from django import template
422
423 register = template.Library()
424
425
426 @register.simple_tag
427 def current_time(format_string):
428 return datetime.datetime.now().strftime(format_string)
429
430 A few things to note about the ``simple_tag`` helper function:
431
432 * Checking for the required number of arguments, etc., has already been
433 done by the time our function is called, so we don't need to do that.
434 * The quotes around the argument (if any) have already been stripped away,
435 so we receive a plain string.
436 * If the argument was a template variable, our function is passed the
437 current value of the variable, not the variable itself.
438
439 Unlike other tag utilities, ``simple_tag`` passes its output through
440 :func:`~django.utils.html.conditional_escape` if the template context is in
441 autoescape mode, to ensure correct HTML and protect you from XSS
442 vulnerabilities.
443
444 If additional escaping is not desired, you will need to use
445 :func:`~django.utils.safestring.mark_safe` if you are absolutely sure that your
446 code does not contain XSS vulnerabilities. For building small HTML snippets,
447 use of :func:`~django.utils.html.format_html` instead of ``mark_safe()`` is
448 strongly recommended.
449
450 If your template tag needs to access the current context, you can use the
451 ``takes_context`` argument when registering your tag::
452
453 @register.simple_tag(takes_context=True)
454 def current_time(context, format_string):
455 timezone = context["timezone"]
456 return your_get_current_time_method(timezone, format_string)
457
458 Note that the first argument *must* be called ``context``.
459
460 For more information on how the ``takes_context`` option works, see the section
461 on :ref:`inclusion tags<howto-custom-template-tags-inclusion-tags>`.
462
463 If you need to rename your tag, you can provide a custom name for it::
464
465 register.simple_tag(lambda x: x - 1, name="minusone")
466
467
468 @register.simple_tag(name="minustwo")
469 def some_function(value):
470 return value - 2
471
472 ``simple_tag`` functions may accept any number of positional or keyword
473 arguments. For example::
474
475 @register.simple_tag
476 def my_tag(a, b, *args, **kwargs):
477 warning = kwargs["warning"]
478 profile = kwargs["profile"]
479 ...
480 return ...
481
482 Then in the template any number of arguments, separated by spaces, may be
483 passed to the template tag. Like in Python, the values for keyword arguments
484 are set using the equal sign ("``=``") and must be provided after the
485 positional arguments. For example:
486
487 .. code-block:: html+django
488
489 {% my_tag 123 "abcd" book.title warning=message|lower profile=user.profile %}
490
491 It's possible to store the tag results in a template variable rather than
492 directly outputting it. This is done by using the ``as`` argument followed by
493 the variable name. Doing so enables you to output the content yourself where
494 you see fit:
495
496 .. code-block:: html+django
497
498 {% current_time "%Y-%m-%d %I:%M %p" as the_time %}
499 <p>The time is {{ the_time }}.</p>
500
501 .. _howto-custom-template-tags-simple-block-tags:
502
503 Simple block tags
504 -----------------
505
506 .. versionadded:: 5.2
507
508 .. method:: django.template.Library.simple_block_tag()
509
510 When a section of rendered template needs to be passed into a custom tag,
511 Django provides the ``simple_block_tag`` helper function to accomplish this.
512 Similar to :meth:`~django.template.Library.simple_tag()`, this function accepts
513 a custom tag function, but with the additional ``content`` argument, which
514 contains the rendered content as defined inside the tag. This allows dynamic
515 template sections to be easily incorporated into custom tags.
516
517 For example, a custom block tag which creates a chart could look like this::
518
519 from django import template
520 from myapp.charts import render_chart
521
522 register = template.Library()
523
524
525 @register.simple_block_tag
526 def chart(content):
527 return render_chart(source=content)
528
529 The ``content`` argument contains everything in between the ``{% chart %}``
530 and ``{% endchart %}`` tags:
531
532 .. code-block:: html+django
533
534 {% chart %}
535 digraph G {
536 label = "Chart for {{ request.user }}"
537 A -> {B C}
538 }
539 {% endchart %}
540
541 If there are other template tags or variables inside the ``content`` block,
542 they will be rendered before being passed to the tag function. In the example
543 above, ``request.user`` will be resolved by the time ``render_chart`` is
544 called.
545
546 Block tags are closed with ``end{name}`` (for example, ``endchart``). This can
547 be customized with the ``end_name`` parameter::
548
549 @register.simple_block_tag(end_name="endofchart")
550 def chart(content):
551 return render_chart(source=content)
552
553 Which would require a template definition like this:
554
555 .. code-block:: html+django
556
557 {% chart %}
558 digraph G {
559 label = "Chart for {{ request.user }}"
560 A -> {B C}
561 }
562 {% endofchart %}
563
564 A few things to note about ``simple_block_tag``:
565
566 * The first argument must be called ``content``, and it will contain the
567 contents of the template tag as a rendered string.
568 * Variables passed to the tag are not included in the rendering context of the
569 content, as would be when using the ``{% with %}`` tag.
570
571 Just like :ref:`simple_tag<howto-custom-template-tags-simple-tags>`,
572 ``simple_block_tag``:
573
574 * Validates the quantity and quality of the arguments.
575 * Strips quotes from arguments if necessary.
576 * Escapes the output accordingly.
577 * Supports passing ``takes_context=True`` at registration time to access
578 context. Note that in this case, the first argument to the custom function
579 *must* be called ``context``, and ``content`` must follow.
580 * Supports renaming the tag by passing the ``name`` argument when registering.
581 * Supports accepting any number of positional or keyword arguments.
582 * Supports storing the result in a template variable using the ``as`` variant.
583
584 .. admonition:: Content Escaping
585
586 ``simple_block_tag`` behaves similarly to ``simple_tag`` regarding
587 auto-escaping. For details on escaping and safety, refer to ``simple_tag``.
588 Because the ``content`` argument has already been rendered by Django, it is
589 already escaped.
590
591 A complete example
592 ~~~~~~~~~~~~~~~~~~
593
594 Consider a custom template tag that generates a message box that supports
595 multiple message levels and content beyond a simple phrase. This could be
596 implemented using a ``simple_block_tag`` as follows:
597
598 .. code-block:: python
599 :caption: ``testapp/templatetags/testapptags.py``
600
601 from django import template
602 from django.utils.html import format_html
603
604 register = template.Library()
605
606
607 @register.simple_block_tag(takes_context=True)
608 def msgbox(context, content, level):
609 format_kwargs = {
610 "level": level.lower(),
611 "level_title": level.capitalize(),
612 "content": content,
613 "open": " open" if level.lower() == "error" else "",
614 "site": context.get("site", "My Site"),
615 }
616 result = """
617 <div class="msgbox {level}">
618 <details{open}>
619 <summary>
620 <strong>{level_title}</strong>: Please read for <i>{site}</i>
621 </summary>
622 <p>
623 {content}
624 </p>
625 </details>
626 </div>
627 """
628 return format_html(result, **format_kwargs)
629
630 When combined with a minimal view and corresponding template, as shown here:
631
632 .. code-block:: python
633 :caption: ``testapp/views.py``
634
635 from django.shortcuts import render
636
637
638 def simpleblocktag_view(request):
639 return render(request, "test.html", context={"site": "Important Site"})
640
641
642 .. code-block:: html+django
643 :caption: ``testapp/templates/test.html``
644
645 {% extends "base.html" %}
646
647 {% load testapptags %}
648
649 {% block content %}
650
651 {% msgbox level="error" %}
652 Please fix all errors. Further documentation can be found at
653 <a href="http://example.com">Docs</a>.
654 {% endmsgbox %}
655
656 {% msgbox level="info" %}
657 More information at: <a href="http://othersite.com">Other Site</a>/
658 {% endmsgbox %}
659
660 {% endblock %}
661
662 The following HTML is produced as the rendered output:
663
664 .. code-block:: html
665
666 <div class="msgbox error">
667 <details open>
668 <summary>
669 <strong>Error</strong>: Please read for <i>Important Site</i>
670 </summary>
671 <p>
672 Please fix all errors. Further documentation can be found at
673 <a href="http://example.com">Docs</a>.
674 </p>
675 </details>
676 </div>
677
678 <div class="msgbox info">
679 <details>
680 <summary>
681 <strong>Info</strong>: Please read for <i>Important Site</i>
682 </summary>
683 <p>
684 More information at: <a href="http://othersite.com">Other Site</a>
685 </p>
686 </details>
687 </div>
688
689 .. _howto-custom-template-tags-inclusion-tags:
690
691 Inclusion tags
692 --------------
693
694 .. method:: django.template.Library.inclusion_tag()
695
696 Another common type of template tag is the type that displays some data by
697 rendering *another* template. For example, Django's admin interface uses custom
698 template tags to display the buttons along the bottom of the "add/change" form
699 pages. Those buttons always look the same, but the link targets change
700 depending on the object being edited -- so they're a perfect case for using a
701 small template that is filled with details from the current object. (In the
702 admin's case, this is the ``submit_row`` tag.)
703
704 These sorts of tags are called "inclusion tags".
705
706 Writing inclusion tags is probably best demonstrated by example. Let's write a
707 tag that outputs a list of choices for a given ``Poll`` object, such as was
708 created in the :ref:`tutorials <creating-models>`. We'll use the tag like this:
709
710 .. code-block:: html+django
711
712 {% show_results poll %}
713
714 ...and the output will be something like this:
715
716 .. code-block:: html
717
718 <ul>
719 <li>First choice</li>
720 <li>Second choice</li>
721 <li>Third choice</li>
722 </ul>
723
724 First, define the function that takes the argument and produces a dictionary of
725 data for the result. The important point here is we only need to return a
726 dictionary, not anything more complex. This will be used as a template context
727 for the template fragment. Example::
728
729 def show_results(poll):
730 choices = poll.choice_set.all()
731 return {"choices": choices}
732
733 Next, create the template used to render the tag's output. This template is a
734 fixed feature of the tag: the tag writer specifies it, not the template
735 designer. Following our example, the template is very short:
736
737 .. code-block:: html+django
738
739 <ul>
740 {% for choice in choices %}
741 <li> {{ choice }} </li>
742 {% endfor %}
743 </ul>
744
745 Now, create and register the inclusion tag by calling the ``inclusion_tag()``
746 method on a ``Library`` object. Following our example, if the above template is
747 in a file called ``results.html`` in a directory that's searched by the
748 template loader, we'd register the tag like this::
749
750 # Here, register is a django.template.Library instance, as before
751 @register.inclusion_tag("results.html")
752 def show_results(poll): ...
753
754 Alternatively it is possible to register the inclusion tag using a
755 :class:`django.template.Template` instance::
756
757 from django.template.loader import get_template
758
759 t = get_template("results.html")
760 register.inclusion_tag(t)(show_results)
761
762 ...when first creating the function.
763
764 Sometimes, your inclusion tags might require a large number of arguments,
765 making it a pain for template authors to pass in all the arguments and remember
766 their order. To solve this, Django provides a ``takes_context`` option for
767 inclusion tags. If you specify ``takes_context`` in creating a template tag,
768 the tag will have no required arguments, and the underlying Python function
769 will have one argument -- the template context as of when the tag was called.
770
771 For example, say you're writing an inclusion tag that will always be used in a
772 context that contains ``home_link`` and ``home_title`` variables that point
773 back to the main page. Here's what the Python function would look like::
774
775 @register.inclusion_tag("link.html", takes_context=True)
776 def jump_link(context):
777 return {
778 "link": context["home_link"],
779 "title": context["home_title"],
780 }
781
782 Note that the first parameter to the function *must* be called ``context``.
783
784 In that ``register.inclusion_tag()`` line, we specified ``takes_context=True``
785 and the name of the template. Here's what the template ``link.html`` might look
786 like:
787
788 .. code-block:: html+django
789
790 Jump directly to <a href="{{ link }}">{{ title }}</a>.
791
792 Then, any time you want to use that custom tag, load its library and call it
793 without any arguments, like so:
794
795 .. code-block:: html+django
796
797 {% jump_link %}
798
799 Note that when you're using ``takes_context=True``, there's no need to pass
800 arguments to the template tag. It automatically gets access to the context.
801
802 The ``takes_context`` parameter defaults to ``False``. When it's set to
803 ``True``, the tag is passed the context object, as in this example. That's the
804 only difference between this case and the previous ``inclusion_tag`` example.
805
806 ``inclusion_tag`` functions may accept any number of positional or keyword
807 arguments. For example::
808
809 @register.inclusion_tag("my_template.html")
810 def my_tag(a, b, *args, **kwargs):
811 warning = kwargs["warning"]
812 profile = kwargs["profile"]
813 ...
814 return ...
815
816 Then in the template any number of arguments, separated by spaces, may be
817 passed to the template tag. Like in Python, the values for keyword arguments
818 are set using the equal sign ("``=``") and must be provided after the
819 positional arguments. For example:
820
821 .. code-block:: html+django
822
823 {% my_tag 123 "abcd" book.title warning=message|lower profile=user.profile %}
824
825 Advanced custom template tags
826 -----------------------------
827
828 Sometimes the basic features for custom template tag creation aren't enough.
829 Don't worry, Django gives you complete access to the internals required to build
830 a template tag from the ground up.
831
832 A quick overview
833 ----------------
834
835 The template system works in a two-step process: compiling and rendering. To
836 define a custom template tag, you specify how the compilation works and how
837 the rendering works.
838
839 When Django compiles a template, it splits the raw template text into
840 ''nodes''. Each node is an instance of ``django.template.Node`` and has
841 a ``render()`` method. A compiled template is a list of ``Node`` objects. When
842 you call ``render()`` on a compiled template object, the template calls
843 ``render()`` on each ``Node`` in its node list, with the given context. The
844 results are all concatenated together to form the output of the template.
845
846 Thus, to define a custom template tag, you specify how the raw template tag is
847 converted into a ``Node`` (the compilation function), and what the node's
848 ``render()`` method does.
849
850 Writing the compilation function
851 --------------------------------
852
853 For each template tag the template parser encounters, it calls a Python
854 function with the tag contents and the parser object itself. This function is
855 responsible for returning a ``Node`` instance based on the contents of the tag.
856
857 For example, let's write a full implementation of our template tag,
858 ``{% current_time %}``, that displays the current date/time, formatted according
859 to a parameter given in the tag, in :func:`~time.strftime` syntax. It's a good
860 idea to decide the tag syntax before anything else. In our case, let's say the
861 tag should be used like this:
862
863 .. code-block:: html+django
864
865 <p>The time is {% current_time "%Y-%m-%d %I:%M %p" %}.</p>
866
867 The parser for this function should grab the parameter and create a ``Node``
868 object::
869
870 from django import template
871
872
873 def do_current_time(parser, token):
874 try:
875 # split_contents() knows not to split quoted strings.
876 tag_name, format_string = token.split_contents()
877 except ValueError:
878 raise template.TemplateSyntaxError(
879 "%r tag requires a single argument" % token.contents.split()[0]
880 )
881 if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")):
882 raise template.TemplateSyntaxError(
883 "%r tag's argument should be in quotes" % tag_name
884 )
885 return CurrentTimeNode(format_string[1:-1])
886
887 Notes:
888
889 * ``parser`` is the template parser object. We don't need it in this
890 example.
891
892 * ``token.contents`` is a string of the raw contents of the tag. In our
893 example, it's ``'current_time "%Y-%m-%d %I:%M %p"'``.
894
895 * The ``token.split_contents()`` method separates the arguments on spaces
896 while keeping quoted strings together. The more straightforward
897 ``token.contents.split()`` wouldn't be as robust, as it would naively
898 split on *all* spaces, including those within quoted strings. It's a good
899 idea to always use ``token.split_contents()``.
900
901 * This function is responsible for raising
902 ``django.template.TemplateSyntaxError``, with helpful messages, for
903 any syntax error.
904
905 * The ``TemplateSyntaxError`` exceptions use the ``tag_name`` variable.
906 Don't hard-code the tag's name in your error messages, because that
907 couples the tag's name to your function. ``token.contents.split()[0]``
908 will ''always'' be the name of your tag -- even when the tag has no
909 arguments.
910
911 * The function returns a ``CurrentTimeNode`` with everything the node needs
912 to know about this tag. In this case, it passes the argument --
913 ``"%Y-%m-%d %I:%M %p"``. The leading and trailing quotes from the
914 template tag are removed in ``format_string[1:-1]``.
915
916 * The parsing is very low-level. The Django developers have experimented
917 with writing small frameworks on top of this parsing system, using
918 techniques such as EBNF grammars, but those experiments made the template
919 engine too slow. It's low-level because that's fastest.
920
921 Writing the renderer
922 --------------------
923
924 The second step in writing custom tags is to define a ``Node`` subclass that
925 has a ``render()`` method.
926
927 Continuing the above example, we need to define ``CurrentTimeNode``::
928
929 import datetime
930 from django import template
931
932
933 class CurrentTimeNode(template.Node):
934 def __init__(self, format_string):
935 self.format_string = format_string
936
937 def render(self, context):
938 return datetime.datetime.now().strftime(self.format_string)
939
940 Notes:
941
942 * ``__init__()`` gets the ``format_string`` from ``do_current_time()``.
943 Always pass any options/parameters/arguments to a ``Node`` via its
944 ``__init__()``.
945
946 * The ``render()`` method is where the work actually happens.
947
948 * ``render()`` should generally fail silently, particularly in a production
949 environment. In some cases however, particularly if
950 ``context.template.engine.debug`` is ``True``, this method may raise an
951 exception to make debugging easier. For example, several core tags raise
952 ``django.template.TemplateSyntaxError`` if they receive the wrong number or
953 type of arguments.
954
955 Ultimately, this decoupling of compilation and rendering results in an
956 efficient template system, because a template can render multiple contexts
957 without having to be parsed multiple times.
958
959 .. _tags-auto-escaping:
960
961 Auto-escaping considerations
962 ----------------------------
963
964 The output from template tags is **not** automatically run through the
965 auto-escaping filters (with the exception of
966 :meth:`~django.template.Library.simple_tag` as described above). However, there
967 are still a couple of things you should keep in mind when writing a template
968 tag.
969
970 If the ``render()`` method of your template tag stores the result in a context
971 variable (rather than returning the result in a string), it should take care
972 to call ``mark_safe()`` if appropriate. When the variable is ultimately
973 rendered, it will be affected by the auto-escape setting in effect at the
974 time, so content that should be safe from further escaping needs to be marked
975 as such.
976
977 Also, if your template tag creates a new context for performing some
978 sub-rendering, set the auto-escape attribute to the current context's value.
979 The ``__init__`` method for the ``Context`` class takes a parameter called
980 ``autoescape`` that you can use for this purpose. For example::
981
982 from django.template import Context
983
984
985 def render(self, context):
986 # ...
987 new_context = Context({"var": obj}, autoescape=context.autoescape)
988 # ... Do something with new_context ...
989
990 This is not a very common situation, but it's useful if you're rendering a
991 template yourself. For example::
992
993 def render(self, context):
994 t = context.template.engine.get_template("small_fragment.html")
995 return t.render(Context({"var": obj}, autoescape=context.autoescape))
996
997 If we had neglected to pass in the current ``context.autoescape`` value to our
998 new ``Context`` in this example, the results would have *always* been
999 automatically escaped, which may not be the desired behavior if the template
1000 tag is used inside a :ttag:`{% autoescape off %}<autoescape>` block.
1001
1002 .. _template_tag_thread_safety:
1003
1004 Thread-safety considerations
1005 ----------------------------
1006
1007 Once a node is parsed, its ``render`` method may be called any number of times.
1008 Since Django is sometimes run in multi-threaded environments, a single node may
1009 be simultaneously rendering with different contexts in response to two separate
1010 requests. Therefore, it's important to make sure your template tags are thread
1011 safe.
1012
1013 To make sure your template tags are thread safe, you should never store state
1014 information on the node itself. For example, Django provides a builtin
1015 :ttag:`cycle` template tag that cycles among a list of given strings each time
1016 it's rendered:
1017
1018 .. code-block:: html+django
1019
1020 {% for o in some_list %}
1021 <tr class="{% cycle 'row1' 'row2' %}">
1022 ...
1023 </tr>
1024 {% endfor %}
1025
1026 A naive implementation of ``CycleNode`` might look something like this::
1027
1028 import itertools
1029 from django import template
1030
1031
1032 class CycleNode(template.Node):
1033 def __init__(self, cyclevars):
1034 self.cycle_iter = itertools.cycle(cyclevars)
1035
1036 def render(self, context):
1037 return next(self.cycle_iter)
1038
1039 But, suppose we have two templates rendering the template snippet from above at
1040 the same time:
1041
1042 #. Thread 1 performs its first loop iteration, ``CycleNode.render()``
1043 returns 'row1'
1044 #. Thread 2 performs its first loop iteration, ``CycleNode.render()``
1045 returns 'row2'
1046 #. Thread 1 performs its second loop iteration, ``CycleNode.render()``
1047 returns 'row1'
1048 #. Thread 2 performs its second loop iteration, ``CycleNode.render()``
1049 returns 'row2'
1050
1051 The CycleNode is iterating, but it's iterating globally. As far as Thread 1
1052 and Thread 2 are concerned, it's always returning the same value. This is
1053 not what we want!
1054
1055 To address this problem, Django provides a ``render_context`` that's associated
1056 with the ``context`` of the template that is currently being rendered. The
1057 ``render_context`` behaves like a Python dictionary, and should be used to
1058 store ``Node`` state between invocations of the ``render`` method.
1059
1060 Let's refactor our ``CycleNode`` implementation to use the ``render_context``::
1061
1062 class CycleNode(template.Node):
1063 def __init__(self, cyclevars):
1064 self.cyclevars = cyclevars
1065
1066 def render(self, context):
1067 if self not in context.render_context:
1068 context.render_context[self] = itertools.cycle(self.cyclevars)
1069 cycle_iter = context.render_context[self]
1070 return next(cycle_iter)
1071
1072 Note that it's perfectly safe to store global information that will not change
1073 throughout the life of the ``Node`` as an attribute. In the case of
1074 ``CycleNode``, the ``cyclevars`` argument doesn't change after the ``Node`` is
1075 instantiated, so we don't need to put it in the ``render_context``. But state
1076 information that is specific to the template that is currently being rendered,
1077 like the current iteration of the ``CycleNode``, should be stored in the
1078 ``render_context``.
1079
1080 .. note::
1081 Notice how we used ``self`` to scope the ``CycleNode`` specific information
1082 within the ``render_context``. There may be multiple ``CycleNodes`` in a
1083 given template, so we need to be careful not to clobber another node's
1084 state information. The easiest way to do this is to always use ``self`` as
1085 the key into ``render_context``. If you're keeping track of several state
1086 variables, make ``render_context[self]`` a dictionary.
1087
1088 Registering the tag
1089 -------------------
1090
1091 Finally, register the tag with your module's ``Library`` instance, as explained
1092 in :ref:`writing custom template tags<howto-writing-custom-template-tags>`
1093 above. Example::
1094
1095 register.tag("current_time", do_current_time)
1096
1097 The ``tag()`` method takes two arguments:
1098
1099 1. The name of the template tag -- a string. If this is left out, the
1100 name of the compilation function will be used.
1101 2. The compilation function -- a Python function (not the name of the
1102 function as a string).
1103
1104 As with filter registration, it is also possible to use this as a decorator::
1105
1106 @register.tag(name="current_time")
1107 def do_current_time(parser, token): ...
1108
1109
1110 @register.tag
1111 def shout(parser, token): ...
1112
1113 If you leave off the ``name`` argument, as in the second example above, Django
1114 will use the function's name as the tag name.
1115
1116 Passing template variables to the tag
1117 -------------------------------------
1118
1119 Although you can pass any number of arguments to a template tag using
1120 ``token.split_contents()``, the arguments are all unpacked as
1121 string literals. A little more work is required in order to pass dynamic
1122 content (a template variable) to a template tag as an argument.
1123
1124 While the previous examples have formatted the current time into a string and
1125 returned the string, suppose you wanted to pass in a
1126 :class:`~django.db.models.DateTimeField` from an object and have the template
1127 tag format that date-time:
1128
1129 .. code-block:: html+django
1130
1131 <p>This post was last updated at {% format_time blog_entry.date_updated "%Y-%m-%d %I:%M %p" %}.</p>
1132
1133 Initially, ``token.split_contents()`` will return three values:
1134
1135 1. The tag name ``format_time``.
1136 2. The string ``'blog_entry.date_updated'`` (without the surrounding
1137 quotes).
1138 3. The formatting string ``'"%Y-%m-%d %I:%M %p"'``. The return value from
1139 ``split_contents()`` will include the leading and trailing quotes for
1140 string literals like this.
1141
1142 Now your tag should begin to look like this::
1143
1144 from django import template
1145
1146
1147 def do_format_time(parser, token):
1148 try:
1149 # split_contents() knows not to split quoted strings.
1150 tag_name, date_to_be_formatted, format_string = token.split_contents()
1151 except ValueError:
1152 raise template.TemplateSyntaxError(
1153 "%r tag requires exactly two arguments" % token.contents.split()[0]
1154 )
1155 if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")):
1156 raise template.TemplateSyntaxError(
1157 "%r tag's argument should be in quotes" % tag_name
1158 )
1159 return FormatTimeNode(date_to_be_formatted, format_string[1:-1])
1160
1161 You also have to change the renderer to retrieve the actual contents of the
1162 ``date_updated`` property of the ``blog_entry`` object. This can be
1163 accomplished by using the ``Variable()`` class in ``django.template``.
1164
1165 To use the ``Variable`` class, instantiate it with the name of the variable to
1166 be resolved, and then call ``variable.resolve(context)``. So, for example::
1167
1168 class FormatTimeNode(template.Node):
1169 def __init__(self, date_to_be_formatted, format_string):
1170 self.date_to_be_formatted = template.Variable(date_to_be_formatted)
1171 self.format_string = format_string
1172
1173 def render(self, context):
1174 try:
1175 actual_date = self.date_to_be_formatted.resolve(context)
1176 return actual_date.strftime(self.format_string)
1177 except template.VariableDoesNotExist:
1178 return ""
1179
1180 Variable resolution will throw a ``VariableDoesNotExist`` exception if it
1181 cannot resolve the string passed to it in the current context of the page.
1182
1183 Setting a variable in the context
1184 ---------------------------------
1185
1186 The above examples output a value. Generally, it's more flexible if your
1187 template tags set template variables instead of outputting values. That way,
1188 template authors can reuse the values that your template tags create.
1189
1190 To set a variable in the context, use dictionary assignment on the context
1191 object in the ``render()`` method. Here's an updated version of
1192 ``CurrentTimeNode`` that sets a template variable ``current_time`` instead of
1193 outputting it::
1194
1195 import datetime
1196 from django import template
1197
1198
1199 class CurrentTimeNode2(template.Node):
1200 def __init__(self, format_string):
1201 self.format_string = format_string
1202
1203 def render(self, context):
1204 context["current_time"] = datetime.datetime.now().strftime(self.format_string)
1205 return ""
1206
1207 Note that ``render()`` returns the empty string. ``render()`` should always
1208 return string output. If all the template tag does is set a variable,
1209 ``render()`` should return the empty string.
1210
1211 Here's how you'd use this new version of the tag:
1212
1213 .. code-block:: html+django
1214
1215 {% current_time "%Y-%m-%d %I:%M %p" %}<p>The time is {{ current_time }}.</p>
1216
1217 .. admonition:: Variable scope in context
1218
1219 Any variable set in the context will only be available in the same
1220 ``block`` of the template in which it was assigned. This behavior is
1221 intentional; it provides a scope for variables so that they don't conflict
1222 with context in other blocks.
1223
1224 But, there's a problem with ``CurrentTimeNode2``: The variable name
1225 ``current_time`` is hard-coded. This means you'll need to make sure your
1226 template doesn't use ``{{ current_time }}`` anywhere else, because the
1227 ``{% current_time %}`` will blindly overwrite that variable's value. A cleaner
1228 solution is to make the template tag specify the name of the output variable,
1229 like so:
1230
1231 .. code-block:: html+django
1232
1233 {% current_time "%Y-%m-%d %I:%M %p" as my_current_time %}
1234 <p>The current time is {{ my_current_time }}.</p>
1235
1236 To do that, you'll need to refactor both the compilation function and ``Node``
1237 class, like so::
1238
1239 import re
1240
1241
1242 class CurrentTimeNode3(template.Node):
1243 def __init__(self, format_string, var_name):
1244 self.format_string = format_string
1245 self.var_name = var_name
1246
1247 def render(self, context):
1248 context[self.var_name] = datetime.datetime.now().strftime(self.format_string)
1249 return ""
1250
1251
1252 def do_current_time(parser, token):
1253 # This version uses a regular expression to parse tag contents.
1254 try:
1255 # Splitting by None == splitting by spaces.
1256 tag_name, arg = token.contents.split(None, 1)
1257 except ValueError:
1258 raise template.TemplateSyntaxError(
1259 "%r tag requires arguments" % token.contents.split()[0]
1260 )
1261 m = re.search(r"(.*?) as (\w+)", arg)
1262 if not m:
1263 raise template.TemplateSyntaxError("%r tag had invalid arguments" % tag_name)
1264 format_string, var_name = m.groups()
1265 if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")):
1266 raise template.TemplateSyntaxError(
1267 "%r tag's argument should be in quotes" % tag_name
1268 )
1269 return CurrentTimeNode3(format_string[1:-1], var_name)
1270
1271 The difference here is that ``do_current_time()`` grabs the format string and
1272 the variable name, passing both to ``CurrentTimeNode3``.
1273
1274 Finally, if you only need to have a simple syntax for your custom
1275 context-updating template tag, consider using the
1276 :meth:`~django.template.Library.simple_tag` shortcut, which supports assigning
1277 the tag results to a template variable.
1278
1279 Parsing until another block tag
1280 -------------------------------
1281
1282 Template tags can work in tandem. For instance, the standard
1283 :ttag:`{% comment %}<comment>` tag hides everything until ``{% endcomment %}``.
1284 To create a template tag such as this, use ``parser.parse()`` in your
1285 compilation function.
1286
1287 Here's how a simplified ``{% comment %}`` tag might be implemented::
1288
1289 def do_comment(parser, token):
1290 nodelist = parser.parse(("endcomment",))
1291 parser.delete_first_token()
1292 return CommentNode()
1293
1294
1295 class CommentNode(template.Node):
1296 def render(self, context):
1297 return ""
1298
1299 .. note::
1300 The actual implementation of :ttag:`{% comment %}<comment>` is slightly
1301 different in that it allows broken template tags to appear between
1302 ``{% comment %}`` and ``{% endcomment %}``. It does so by calling
1303 ``parser.skip_past('endcomment')`` instead of ``parser.parse(('endcomment',))``
1304 followed by ``parser.delete_first_token()``, thus avoiding the generation of a
1305 node list.
1306
1307 ``parser.parse()`` takes a tuple of names of block tags ''to parse until''. It
1308 returns an instance of ``django.template.NodeList``, which is a list of
1309 all ``Node`` objects that the parser encountered ''before'' it encountered
1310 any of the tags named in the tuple.
1311
1312 In ``"nodelist = parser.parse(('endcomment',))"`` in the above example,
1313 ``nodelist`` is a list of all nodes between the ``{% comment %}`` and
1314 ``{% endcomment %}``, not counting ``{% comment %}`` and ``{% endcomment %}``
1315 themselves.
1316
1317 After ``parser.parse()`` is called, the parser hasn't yet "consumed" the
1318 ``{% endcomment %}`` tag, so the code needs to explicitly call
1319 ``parser.delete_first_token()``.
1320
1321 ``CommentNode.render()`` returns an empty string. Anything between
1322 ``{% comment %}`` and ``{% endcomment %}`` is ignored.
1323
1324 Parsing until another block tag, and saving contents
1325 ----------------------------------------------------
1326
1327 In the previous example, ``do_comment()`` discarded everything between
1328 ``{% comment %}`` and ``{% endcomment %}``. Instead of doing that, it's
1329 possible to do something with the code between block tags.
1330
1331 For example, here's a custom template tag, ``{% upper %}``, that capitalizes
1332 everything between itself and ``{% endupper %}``.
1333
1334 Usage:
1335
1336 .. code-block:: html+django
1337
1338 {% upper %}This will appear in uppercase, {{ your_name }}.{% endupper %}
1339
1340 As in the previous example, we'll use ``parser.parse()``. But this time, we
1341 pass the resulting ``nodelist`` to the ``Node``::
1342
1343 def do_upper(parser, token):
1344 nodelist = parser.parse(("endupper",))
1345 parser.delete_first_token()
1346 return UpperNode(nodelist)
1347
1348
1349 class UpperNode(template.Node):
1350 def __init__(self, nodelist):
1351 self.nodelist = nodelist
1352
1353 def render(self, context):
1354 output = self.nodelist.render(context)
1355 return output.upper()
1356
1357 The only new concept here is the ``self.nodelist.render(context)`` in
1358 ``UpperNode.render()``.
1359
1360 For more examples of complex rendering, see the source code of
1361 :ttag:`{% for %}<for>` in :source:`django/template/defaulttags.py` and
1362 :ttag:`{% if %}<if>` in :source:`django/template/smartif.py`.