1 ====================================================
2 The Django template language: For Python programmers
3 ====================================================
5 This document explains the Django template system from a technical
6 perspective -- how it works and how to extend it. If you're just looking for
7 reference on the language syntax, see
8 `The Django template language: For template authors`_.
10 If you're looking to use the Django template system as part of another
11 application -- i.e., without the rest of the framework -- make sure to read
12 the `configuration`_ section later in this document.
14 .. _`The Django template language: For template authors`: ../templates/
19 A **template** is a text document, or a normal Python string, that is marked-up
20 using the Django template language. A template can contain **block tags** or
23 A **block tag** is a symbol within a template that does something.
25 This definition is deliberately vague. For example, a block tag can output
26 content, serve as a control structure (an "if" statement or "for" loop), grab
27 content from a database or enable access to other template tags.
29 Block tags are surrounded by ``"{%"`` and ``"%}"``.
31 Example template with block tags::
33 {% if is_logged_in %}Thanks for logging in!{% else %}Please log in.{% endif %}
35 A **variable** is a symbol within a template that outputs a value.
37 Variable tags are surrounded by ``"{{"`` and ``"}}"``.
39 Example template with variables::
41 My first name is {{ first_name }}. My last name is {{ last_name }}.
43 A **context** is a "variable name" -> "variable value" mapping that is passed
46 A template **renders** a context by replacing the variable "holes" with values
47 from the context and executing all block tags.
49 Using the template system
50 =========================
52 Using the template system in Python is a two-step process:
54 * First, you compile the raw template code into a ``Template`` object.
55 * Then, you call the ``render()`` method of the ``Template`` object with a
61 The easiest way to create a ``Template`` object is by instantiating it
62 directly. The class lives at ``django.template.Template``. The constructor
63 takes one argument -- the raw template code::
65 >>> from django.template import Template
66 >>> t = Template("My name is {{ my_name }}.")
68 <django.template.Template instance>
70 .. admonition:: Behind the scenes
72 The system only parses your raw template code once -- when you create the
73 ``Template`` object. From then on, it's stored internally as a "node"
74 structure for performance.
76 Even the parsing itself is quite fast. Most of the parsing happens via a
77 single call to a single, short, regular expression.
82 Once you have a compiled ``Template`` object, you can render a context -- or
83 multiple contexts -- with it. The ``Context`` class lives at
84 ``django.template.Context``, and the constructor takes one (optional)
85 argument: a dictionary mapping variable names to variable values. Call the
86 ``Template`` object's ``render()`` method with the context to "fill" the
89 >>> from django.template import Context, Template
90 >>> t = Template("My name is {{ my_name }}.")
92 >>> c = Context({"my_name": "Adrian"})
96 >>> c = Context({"my_name": "Dolores"})
100 Variable names must consist of any letter (A-Z), any digit (0-9), an underscore
103 Dots have a special meaning in template rendering. A dot in a variable name
104 signifies **lookup**. Specifically, when the template system encounters a dot
105 in a variable name, it tries the following lookups, in this order:
107 * Dictionary lookup. Example: ``foo["bar"]``
108 * Attribute lookup. Example: ``foo.bar``
109 * Method call. Example: ``foo.bar()``
110 * List-index lookup. Example: ``foo[bar]``
112 The template system uses the first lookup type that works. It's short-circuit
115 Here are a few examples::
117 >>> from django.template import Context, Template
118 >>> t = Template("My name is {{ person.first_name }}.")
119 >>> d = {"person": {"first_name": "Joe", "last_name": "Johnson"}}
120 >>> t.render(Context(d))
123 >>> class PersonClass: pass
124 >>> p = PersonClass()
125 >>> p.first_name = "Ron"
126 >>> p.last_name = "Nasty"
127 >>> t.render(Context({"person": p}))
130 >>> class PersonClass2:
131 ... def first_name(self):
132 ... return "Samantha"
133 >>> p = PersonClass2()
134 >>> t.render(Context({"person": p}))
135 "My name is Samantha."
137 >>> t = Template("The first stooge in the list is {{ stooges.0 }}.")
138 >>> c = Context({"stooges": ["Larry", "Curly", "Moe"]})
140 "The first stooge in the list is Larry."
142 Method lookups are slightly more complex than the other lookup types. Here are
143 some things to keep in mind:
145 * If, during the method lookup, a method raises an exception, the exception
146 will be propagated, unless the exception has an attribute
147 ``silent_variable_failure`` whose value is ``True``. If the exception
148 *does* have a ``silent_variable_failure`` attribute, the variable will
149 render as an empty string. Example::
151 >>> t = Template("My name is {{ person.first_name }}.")
152 >>> class PersonClass3:
153 ... def first_name(self):
154 ... raise AssertionError, "foo"
155 >>> p = PersonClass3()
156 >>> t.render(Context({"person": p}))
157 Traceback (most recent call last):
161 >>> class SilentAssertionError(Exception):
162 ... silent_variable_failure = True
163 >>> class PersonClass4:
164 ... def first_name(self):
165 ... raise SilentAssertionError
166 >>> p = PersonClass4()
167 >>> t.render(Context({"person": p}))
170 Note that ``django.core.exceptions.ObjectDoesNotExist``, which is the
171 base class for all Django database API ``DoesNotExist`` exceptions, has
172 ``silent_variable_failure = True``. So if you're using Django templates
173 with Django model objects, any ``DoesNotExist`` exception will fail
176 * A method call will only work if the method has no required arguments.
177 Otherwise, the system will move to the next lookup type (list-index
180 * Obviously, some methods have side effects, and it'd be either foolish or
181 a security hole to allow the template system to access them.
183 A good example is the ``delete()`` method on each Django model object.
184 The template system shouldn't be allowed to do something like this::
186 I will now delete this valuable data. {{ data.delete }}
188 To prevent this, set a function attribute ``alters_data`` on the method.
189 The template system won't execute a method if the method has
190 ``alters_data=True`` set. The dynamically-generated ``delete()`` and
191 ``save()`` methods on Django model objects get ``alters_data=True``
192 automatically. Example::
194 def sensitive_function(self):
195 self.database_record.delete()
196 sensitive_function.alters_data = True
198 How invalid variables are handled
199 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
201 Generally, if a variable doesn't exist, the template system inserts the
202 value of the ``TEMPLATE_STRING_IF_INVALID`` setting, which is set to ``''``
203 (the empty string) by default.
205 Filters that are applied to an invalid variable will only be applied if
206 ``TEMPLATE_STRING_IF_INVALID`` is set to ``''`` (the empty string). If
207 ``TEMPLATE_STRING_IF_INVALID`` is set to any other value, variable
208 filters will be ignored.
210 This behavior is slightly different for the ``if``, ``for`` and ``regroup``
211 template tags. If an invalid variable is provided to one of these template
212 tags, the variable will be interpreted as ``None``. Filters are always
213 applied to invalid variables within these template tags.
215 If ``TEMPLATE_STRING_IF_INVALID`` contains a ``'%s'``, the format marker will
216 be replaced with the name of the invalid variable.
218 .. admonition:: For debug purposes only!
220 While ``TEMPLATE_STRING_IF_INVALID`` can be a useful debugging tool,
221 it is a bad idea to turn it on as a 'development default'.
223 Many templates, including those in the Admin site, rely upon the
224 silence of the template system when a non-existent variable is
225 encountered. If you assign a value other than ``''`` to
226 ``TEMPLATE_STRING_IF_INVALID``, you will experience rendering
227 problems with these templates and sites.
229 Generally, ``TEMPLATE_STRING_IF_INVALID`` should only be enabled
230 in order to debug a specific template problem, then cleared
231 once debugging is complete.
233 Playing with Context objects
234 ----------------------------
236 Most of the time, you'll instantiate ``Context`` objects by passing in a
237 fully-populated dictionary to ``Context()``. But you can add and delete items
238 from a ``Context`` object once it's been instantiated, too, using standard
241 >>> c = Context({"foo": "bar"})
247 >>> c['newvariable'] = 'hello'
251 A ``Context`` object is a stack. That is, you can ``push()`` and ``pop()`` it.
252 If you ``pop()`` too much, it'll raise
253 ``django.template.ContextPopException``::
256 >>> c['foo'] = 'first level'
258 >>> c['foo'] = 'second level'
264 >>> c['foo'] = 'overwritten'
268 Traceback (most recent call last):
270 django.template.ContextPopException
272 Using a ``Context`` as a stack comes in handy in some custom template tags, as
275 Subclassing Context: RequestContext
276 -----------------------------------
278 Django comes with a special ``Context`` class,
279 ``django.template.RequestContext``, that acts slightly differently than
280 the normal ``django.template.Context``. The first difference is that it takes
281 an `HttpRequest object`_ as its first argument. For example::
283 c = RequestContext(request, {
287 The second difference is that it automatically populates the context with a few
288 variables, according to your `TEMPLATE_CONTEXT_PROCESSORS setting`_.
290 The ``TEMPLATE_CONTEXT_PROCESSORS`` setting is a tuple of callables -- called
291 **context processors** -- that take a request object as their argument and
292 return a dictionary of items to be merged into the context. By default,
293 ``TEMPLATE_CONTEXT_PROCESSORS`` is set to::
295 ("django.core.context_processors.auth",
296 "django.core.context_processors.debug",
297 "django.core.context_processors.i18n",
298 "django.core.context_processors.media")
300 Each processor is applied in order. That means, if one processor adds a
301 variable to the context and a second processor adds a variable with the same
302 name, the second will override the first. The default processors are explained
305 Also, you can give ``RequestContext`` a list of additional processors, using the
306 optional, third positional argument, ``processors``. In this example, the
307 ``RequestContext`` instance gets a ``ip_address`` variable::
309 def ip_address_processor(request):
310 return {'ip_address': request.META['REMOTE_ADDR']}
312 def some_view(request):
314 c = RequestContext(request, {
316 }, [ip_address_processor])
320 If you're using Django's ``render_to_response()`` shortcut to populate a
321 template with the contents of a dictionary, your template will be passed a
322 ``Context`` instance by default (not a ``RequestContext``). To use a
323 ``RequestContext`` in your template rendering, pass an optional third
324 argument to ``render_to_response()``: a ``RequestContext``
325 instance. Your code might look like this::
327 def some_view(request):
329 return render_to_response('my_template.html',
331 context_instance=RequestContext(request))
333 Here's what each of the default processors does:
335 .. _HttpRequest object: ../request_response/#httprequest-objects
336 .. _TEMPLATE_CONTEXT_PROCESSORS setting: ../settings/#template-context-processors
338 django.core.context_processors.auth
339 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
341 If ``TEMPLATE_CONTEXT_PROCESSORS`` contains this processor, every
342 ``RequestContext`` will contain these three variables:
344 * ``user`` -- An ``auth.User`` instance representing the currently
345 logged-in user (or an ``AnonymousUser`` instance, if the client isn't
346 logged in). See the `user authentication docs`_.
348 * ``messages`` -- A list of messages (as strings) for the currently
349 logged-in user. Behind the scenes, this calls
350 ``request.user.get_and_delete_messages()`` for every request. That method
351 collects the user's messages and deletes them from the database.
353 Note that messages are set with ``user.message_set.create``. See the
354 `message docs`_ for more.
356 * ``perms`` -- An instance of
357 ``django.core.context_processors.PermWrapper``, representing the
358 permissions that the currently logged-in user has. See the `permissions
361 .. _user authentication docs: ../authentication/#users
362 .. _message docs: ../authentication/#messages
363 .. _permissions docs: ../authentication/#permissions
365 django.core.context_processors.debug
366 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
368 If ``TEMPLATE_CONTEXT_PROCESSORS`` contains this processor, every
369 ``RequestContext`` will contain these two variables -- but only if your
370 ``DEBUG`` setting is set to ``True`` and the request's IP address
371 (``request.META['REMOTE_ADDR']``) is in the ``INTERNAL_IPS`` setting:
373 * ``debug`` -- ``True``. You can use this in templates to test whether
374 you're in ``DEBUG`` mode.
375 * ``sql_queries`` -- A list of ``{'sql': ..., 'time': ...}`` dictionaries,
376 representing every SQL query that has happened so far during the request
377 and how long it took. The list is in order by query.
379 django.core.context_processors.i18n
380 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
382 If ``TEMPLATE_CONTEXT_PROCESSORS`` contains this processor, every
383 ``RequestContext`` will contain these two variables:
385 * ``LANGUAGES`` -- The value of the `LANGUAGES setting`_.
386 * ``LANGUAGE_CODE`` -- ``request.LANGUAGE_CODE``, if it exists. Otherwise,
387 the value of the `LANGUAGE_CODE setting`_.
389 See the `internationalization docs`_ for more.
391 .. _LANGUAGES setting: ../settings/#languages
392 .. _LANGUAGE_CODE setting: ../settings/#language-code
393 .. _internationalization docs: ../i18n/
395 django.core.context_processors.media
396 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
398 If ``TEMPLATE_CONTEXT_PROCESSORS`` contains this processor, every
399 ``RequestContext`` will contain a variable ``MEDIA_URL``, providing the
400 value of the `MEDIA_URL setting`_.
402 .. _MEDIA_URL setting: ../settings/#media-url
404 django.core.context_processors.request
405 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
407 If ``TEMPLATE_CONTEXT_PROCESSORS`` contains this processor, every
408 ``RequestContext`` will contain a variable ``request``, which is the current
409 `HttpRequest object`_. Note that this processor is not enabled by default;
410 you'll have to activate it.
412 Writing your own context processors
413 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
415 A context processor has a very simple interface: It's just a Python function
416 that takes one argument, an ``HttpRequest`` object, and returns a dictionary
417 that gets added to the template context. Each context processor *must* return
420 Custom context processors can live anywhere in your code base. All Django cares
421 about is that your custom context processors are pointed-to by your
422 ``TEMPLATE_CONTEXT_PROCESSORS`` setting.
427 Generally, you'll store templates in files on your filesystem rather than using
428 the low-level ``Template`` API yourself. Save templates in a directory
429 specified as a **template directory**.
431 Django searches for template directories in a number of places, depending on
432 your template-loader settings (see "Loader types" below), but the most basic
433 way of specifying template directories is by using the ``TEMPLATE_DIRS``
436 The TEMPLATE_DIRS setting
437 ~~~~~~~~~~~~~~~~~~~~~~~~~
439 Tell Django what your template directories are by using the ``TEMPLATE_DIRS``
440 setting in your settings file. This should be set to a list or tuple of strings
441 that contain full paths to your template directory(ies). Example::
444 "/home/html/templates/lawrence.com",
445 "/home/html/templates/default",
448 Your templates can go anywhere you want, as long as the directories and
449 templates are readable by the Web server. They can have any extension you want,
450 such as ``.html`` or ``.txt``, or they can have no extension at all.
452 Note that these paths should use Unix-style forward slashes, even on Windows.
457 Django has two ways to load templates from files:
459 ``django.template.loader.get_template(template_name)``
460 ``get_template`` returns the compiled template (a ``Template`` object) for
461 the template with the given name. If the template doesn't exist, it raises
462 ``django.template.TemplateDoesNotExist``.
464 ``django.template.loader.select_template(template_name_list)``
465 ``select_template`` is just like ``get_template``, except it takes a list
466 of template names. Of the list, it returns the first template that exists.
468 For example, if you call ``get_template('story_detail.html')`` and have the
469 above ``TEMPLATE_DIRS`` setting, here are the files Django will look for, in
472 * ``/home/html/templates/lawrence.com/story_detail.html``
473 * ``/home/html/templates/default/story_detail.html``
475 If you call ``select_template(['story_253_detail.html', 'story_detail.html'])``,
476 here's what Django will look for:
478 * ``/home/html/templates/lawrence.com/story_253_detail.html``
479 * ``/home/html/templates/default/story_253_detail.html``
480 * ``/home/html/templates/lawrence.com/story_detail.html``
481 * ``/home/html/templates/default/story_detail.html``
483 When Django finds a template that exists, it stops looking.
487 You can use ``select_template()`` for super-flexible "templatability." For
488 example, if you've written a news story and want some stories to have
489 custom templates, use something like
490 ``select_template(['story_%s_detail.html' % story.id, 'story_detail.html'])``.
491 That'll allow you to use a custom template for an individual story, with a
492 fallback template for stories that don't have custom templates.
497 It's possible -- and preferable -- to organize templates in subdirectories of
498 the template directory. The convention is to make a subdirectory for each
499 Django app, with subdirectories within those subdirectories as needed.
501 Do this for your own sanity. Storing all templates in the root level of a
502 single directory gets messy.
504 To load a template that's within a subdirectory, just use a slash, like so::
506 get_template('news/story_detail.html')
508 Using the same ``TEMPLATE_DIRS`` setting from above, this example
509 ``get_template()`` call will attempt to load the following templates:
511 * ``/home/html/templates/lawrence.com/news/story_detail.html``
512 * ``/home/html/templates/default/news/story_detail.html``
517 By default, Django uses a filesystem-based template loader, but Django comes
518 with a few other template loaders, which know how to load templates from other
521 These other loaders are disabled by default, but you can activate them by
522 editing your ``TEMPLATE_LOADERS`` setting. ``TEMPLATE_LOADERS`` should be a
523 tuple of strings, where each string represents a template loader. Here are the
524 template loaders that come with Django:
526 ``django.template.loaders.filesystem.load_template_source``
527 Loads templates from the filesystem, according to ``TEMPLATE_DIRS``.
529 ``django.template.loaders.app_directories.load_template_source``
530 Loads templates from Django apps on the filesystem. For each app in
531 ``INSTALLED_APPS``, the loader looks for a ``templates`` subdirectory. If
532 the directory exists, Django looks for templates in there.
534 This means you can store templates with your individual apps. This also
535 makes it easy to distribute Django apps with default templates.
537 For example, for this setting::
539 INSTALLED_APPS = ('myproject.polls', 'myproject.music')
541 ...then ``get_template('foo.html')`` will look for templates in these
542 directories, in this order:
544 * ``/path/to/myproject/polls/templates/foo.html``
545 * ``/path/to/myproject/music/templates/foo.html``
547 Note that the loader performs an optimization when it is first imported:
548 It caches a list of which ``INSTALLED_APPS`` packages have a ``templates``
551 ``django.template.loaders.eggs.load_template_source``
552 Just like ``app_directories`` above, but it loads templates from Python
553 eggs rather than from the filesystem.
555 Django uses the template loaders in order according to the ``TEMPLATE_LOADERS``
556 setting. It uses each loader until a loader finds a match.
558 The ``render_to_string()`` shortcut
559 ===================================
561 To cut down on the repetitive nature of loading and rendering
562 templates, Django provides a shortcut function which largely
563 automates the process: ``render_to_string()`` in
564 ``django.template.loader``, which loads a template, renders it and
565 returns the resulting string::
567 from django.template.loader import render_to_string
568 rendered = render_to_string('my_template.html', { 'foo': 'bar' })
570 The ``render_to_string`` shortcut takes one required argument --
571 ``template_name``, which should be the name of the template to load
572 and render -- and two optional arguments::
575 A dictionary to be used as variables and values for the
576 template's context. This can also be passed as the second
580 An instance of ``Context`` or a subclass (e.g., an instance of
581 ``RequestContext``) to use as the template's context. This can
582 also be passed as the third positional argument.
584 See also the `render_to_response()`_ shortcut, which calls
585 ``render_to_string`` and feeds the result into an ``HttpResponse``
586 suitable for returning directly from a view.
588 .. _render_to_response(): ../shortcuts/#render-to-response
590 Extending the template system
591 =============================
593 Although the Django template language comes with several default tags and
594 filters, you might want to write your own. It's easy to do.
596 First, create a ``templatetags`` package in the appropriate Django app's
597 package. It should be on the same level as ``models.py``, ``views.py``, etc. For
605 Add two files to the ``templatetags`` package: an ``__init__.py`` file and a
606 file that will contain your custom tag/filter definitions. The name of the
607 latter file is the name you'll use to load the tags later. For example, if your
608 custom tags/filters are in a file called ``poll_extras.py``, you'd do the
609 following in a template::
611 {% load poll_extras %}
613 The ``{% load %}`` tag looks at your ``INSTALLED_APPS`` setting and only allows
614 the loading of template libraries within installed Django apps. This is a
615 security feature: It allows you to host Python code for many template libraries
616 on a single computer without enabling access to all of them for every Django
619 If you write a template library that isn't tied to any particular models/views,
620 it's perfectly OK to have a Django app package that only contains a
621 ``templatetags`` package.
623 There's no limit on how many modules you put in the ``templatetags`` package.
624 Just keep in mind that a ``{% load %}`` statement will load tags/filters for
625 the given Python module name, not the name of the app.
627 Once you've created that Python module, you'll just have to write a bit of
628 Python code, depending on whether you're writing filters or tags.
630 To be a valid tag library, the module contain a module-level variable named
631 ``register`` that is a ``template.Library`` instance, in which all the tags and
632 filters are registered. So, near the top of your module, put the following::
634 from django import template
636 register = template.Library()
638 .. admonition:: Behind the scenes
640 For a ton of examples, read the source code for Django's default filters
641 and tags. They're in ``django/template/defaultfilters.py`` and
642 ``django/template/defaulttags.py``, respectively.
644 Writing custom template filters
645 -------------------------------
647 Custom filters are just Python functions that take one or two arguments:
649 * The value of the variable (input) -- not necessarily a string.
650 * The value of the argument -- this can have a default value, or be left
653 For example, in the filter ``{{ var|foo:"bar" }}``, the filter ``foo`` would be
654 passed the variable ``var`` and the argument ``"bar"``.
656 Filter functions should always return something. They shouldn't raise
657 exceptions. They should fail silently. In case of error, they should return
658 either the original input or an empty string -- whichever makes more sense.
660 Here's an example filter definition::
663 "Removes all values of arg from the given string"
664 return value.replace(arg, '')
666 And here's an example of how that filter would be used::
668 {{ somevariable|cut:"0" }}
670 Most filters don't take arguments. In this case, just leave the argument out of
671 your function. Example::
673 def lower(value): # Only one argument.
674 "Converts a string into all lowercase"
677 Template filters that expect strings
678 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
680 If you're writing a template filter that only expects a string as the first
681 argument, you should use the decorator ``stringfilter``. This will
682 convert an object to its string value before being passed to your function::
684 from django.template.defaultfilters import stringfilter
690 This way, you'll be able to pass, say, an integer to this filter, and it
691 won't cause an ``AttributeError`` (because integers don't have ``lower()``
694 Registering a custom filters
695 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
697 Once you've written your filter definition, you need to register it with
698 your ``Library`` instance, to make it available to Django's template language::
700 register.filter('cut', cut)
701 register.filter('lower', lower)
703 The ``Library.filter()`` method takes two arguments:
705 1. The name of the filter -- a string.
706 2. The compilation function -- a Python function (not the name of the
707 function as a string).
709 If you're using Python 2.4 or above, you can use ``register.filter()`` as a
712 @register.filter(name='cut')
715 return value.replace(arg, '')
722 If you leave off the ``name`` argument, as in the second example above, Django
723 will use the function's name as the filter name.
725 Filters and auto-escaping
726 ~~~~~~~~~~~~~~~~~~~~~~~~~
728 **New in Django development version**
730 When you are writing a custom filter, you need to give some thought to how
731 this filter will interact with Django's auto-escaping behaviour. Firstly, you
732 should realise that there are three types of strings that can be passed around
733 inside the template code:
735 * raw strings are the native Python ``str`` or ``unicode`` types. On
736 output, they are escaped if auto-escaping is in effect and presented
737 unchanged, otherwise.
739 * "safe" strings are strings that are safe from further escaping at output
740 time. Any necessary escaping has already been done. They are commonly used
741 for output that contains raw HTML that is intended to be intrepreted on the
744 Internally, these strings are of type ``SafeString`` or ``SafeUnicode``,
745 although they share a common base class in ``SafeData``, so you can test
746 for them using code like::
748 if isinstance(value, SafeData):
749 # Do something with the "safe" string.
751 * strings which are marked as "needing escaping" are *always* escaped on
752 output, regardless of whether they are in an ``autoescape`` block or not.
753 These strings are only escaped once, however, even if auto-escaping
754 applies. This type of string is internally represented by the types
755 ``EscapeString`` and ``EscapeUnicode``. You will not normally need to worry
756 about these; they exist for the implementation of the ``escape`` filter.
758 Inside your filter, you will need to think about three areas in order to be
759 auto-escaping compliant:
761 1. If your filter returns a string that is ready for direct output (it should
762 be considered a "safe" string), you should call
763 ``django.utils.safestring.mark_safe()`` on the result prior to returning.
764 This will turn the result into the appropriate ``SafeData`` type. This is
765 often the case when you are returning raw HTML, for example.
767 2. If your filter is given a "safe" string, is it guaranteed to return a
768 "safe" string? If so, set the ``is_safe`` attribute on the function to be
769 ``True``. For example, a filter that replaced a word consisting only of
770 digits with the number spelt out in words is going to be
771 safe-string-preserving, since it cannot introduce any of the five dangerous
772 characters: <, >, ", ' or &. We can write::
775 def convert_to_words(value):
776 # ... implementation here ...
779 convert_to_words.is_safe = True
781 Note that this filter does not return a universally safe result (it does
782 not return ``mark_safe(result)``) because if it is handed a raw string such
783 as '<a>', this will need further escaping in an auto-escape environment.
784 The ``is_safe`` attribute only talks about the the result when a safe
785 string is passed into the filter.
787 3. Will your filter behave differently depending upon whether auto-escaping
788 is currently in effect or not? This is normally a concern when you are
789 returning mixed content (HTML elements mixed with user-supplied content).
790 For example, the ``ordered_list`` filter that ships with Django needs to
791 know whether to escape its content or not. It will always return a safe
792 string. Since it returns raw HTML, we cannot apply escaping to the
793 result -- it needs to be done in-situ.
795 For these cases, the filter function needs to be told what the current
796 auto-escaping setting is. Set the ``needs_autoescape`` attribute on the
797 filter to ``True`` and have your function take an extra argument called
798 ``autoescape`` with a default value of ``None``. When the filter is called,
799 the ``autoescape`` keyword argument will be ``True`` if auto-escaping is in
800 effect. For example, the ``unordered_list`` filter is written as::
802 def unordered_list(value, autoescape=None):
803 # ... lots of code here ...
805 return mark_safe(...)
807 unordered_list.is_safe = True
808 unordered_list.needs_autoescape = True
810 By default, both the ``is_safe`` and ``needs_autoescape`` attributes are
811 ``False``. You do not need to specify them if ``False`` is an acceptable
814 Writing custom template tags
815 ----------------------------
817 Tags are more complex than filters, because tags can do anything.
822 Above, this document explained that the template system works in a two-step
823 process: compiling and rendering. To define a custom template tag, you specify
824 how the compilation works and how the rendering works.
826 When Django compiles a template, it splits the raw template text into
827 ''nodes''. Each node is an instance of ``django.template.Node`` and has
828 a ``render()`` method. A compiled template is, simply, a list of ``Node``
829 objects. When you call ``render()`` on a compiled template object, the template
830 calls ``render()`` on each ``Node`` in its node list, with the given context.
831 The results are all concatenated together to form the output of the template.
833 Thus, to define a custom template tag, you specify how the raw template tag is
834 converted into a ``Node`` (the compilation function), and what the node's
835 ``render()`` method does.
837 Writing the compilation function
838 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
840 For each template tag the template parser encounters, it calls a Python
841 function with the tag contents and the parser object itself. This function is
842 responsible for returning a ``Node`` instance based on the contents of the tag.
844 For example, let's write a template tag, ``{% current_time %}``, that displays
845 the current date/time, formatted according to a parameter given in the tag, in
846 `strftime syntax`_. It's a good idea to decide the tag syntax before anything
847 else. In our case, let's say the tag should be used like this::
849 <p>The time is {% current_time "%Y-%m-%d %I:%M %p" %}.</p>
851 .. _`strftime syntax`: http://www.python.org/doc/current/lib/module-time.html#l2h-1941
853 The parser for this function should grab the parameter and create a ``Node``
856 from django import template
857 def do_current_time(parser, token):
859 # split_contents() knows not to split quoted strings.
860 tag_name, format_string = token.split_contents()
862 raise template.TemplateSyntaxError, "%r tag requires a single argument" % token.contents.split()[0]
863 if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")):
864 raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
865 return CurrentTimeNode(format_string[1:-1])
869 * ``parser`` is the template parser object. We don't need it in this
872 * ``token.contents`` is a string of the raw contents of the tag. In our
873 example, it's ``'current_time "%Y-%m-%d %I:%M %p"'``.
875 * The ``token.split_contents()`` method separates the arguments on spaces
876 while keeping quoted strings together. The more straightforward
877 ``token.contents.split()`` wouldn't be as robust, as it would naively
878 split on *all* spaces, including those within quoted strings. It's a good
879 idea to always use ``token.split_contents()``.
881 * This function is responsible for raising
882 ``django.template.TemplateSyntaxError``, with helpful messages, for
885 * The ``TemplateSyntaxError`` exceptions use the ``tag_name`` variable.
886 Don't hard-code the tag's name in your error messages, because that
887 couples the tag's name to your function. ``token.contents.split()[0]``
888 will ''always'' be the name of your tag -- even when the tag has no
891 * The function returns a ``CurrentTimeNode`` with everything the node needs
892 to know about this tag. In this case, it just passes the argument --
893 ``"%Y-%m-%d %I:%M %p"``. The leading and trailing quotes from the
894 template tag are removed in ``format_string[1:-1]``.
896 * The parsing is very low-level. The Django developers have experimented
897 with writing small frameworks on top of this parsing system, using
898 techniques such as EBNF grammars, but those experiments made the template
899 engine too slow. It's low-level because that's fastest.
904 The second step in writing custom tags is to define a ``Node`` subclass that
905 has a ``render()`` method.
907 Continuing the above example, we need to define ``CurrentTimeNode``::
909 from django import template
911 class CurrentTimeNode(template.Node):
912 def __init__(self, format_string):
913 self.format_string = format_string
914 def render(self, context):
915 return datetime.datetime.now().strftime(self.format_string)
919 * ``__init__()`` gets the ``format_string`` from ``do_current_time()``.
920 Always pass any options/parameters/arguments to a ``Node`` via its
923 * The ``render()`` method is where the work actually happens.
925 * ``render()`` should never raise ``TemplateSyntaxError`` or any other
926 exception. It should fail silently, just as template filters should.
928 Ultimately, this decoupling of compilation and rendering results in an
929 efficient template system, because a template can render multiple context
930 without having to be parsed multiple times.
932 Auto-escaping considerations
933 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
935 The output from template tags is not automatically run through the
936 auto-escaping filters. However, there are still a couple of things you should
937 keep in mind when writing a template tag:
939 If the ``render()`` function of your template stores the result in a context
940 variable (rather than returning the result in a string), it should take care
941 to call ``mark_safe()`` if appropriate. When the variable is ultimately
942 rendered, it will be affected by the auto-escape setting in effect at the
943 time, so content that should be safe from further escaping needs to be marked
946 Also, if your template tag creates a new context for performing some
947 sub-rendering, you should be careful to set the auto-escape attribute to the
948 current context's value. The ``__init__`` method for the ``Context`` class
949 takes a parameter called ``autoescape`` that you can use for this purpose. For
952 def render(self, context):
954 new_context = Context({'var': obj}, autoescape=context.autoescape)
955 # ... Do something with new_context ...
957 This is not a very common situation, but it is sometimes useful, particularly
958 if you are rendering a template yourself. For example::
960 def render(self, context):
961 t = template.load_template('small_fragment.html')
962 return t.render(Context({'var': obj}, autoescape=context.autoescape))
964 If we had neglected to pass in the current ``context.autoescape`` value to our
965 new ``Context`` in this example, the results would have *always* been
966 automatically escaped, which may not be the desired behaviour if the template
967 tag is used inside a ``{% autoescape off %}`` block.
972 Finally, register the tag with your module's ``Library`` instance, as explained
973 in "Writing custom template filters" above. Example::
975 register.tag('current_time', do_current_time)
977 The ``tag()`` method takes two arguments:
979 1. The name of the template tag -- a string. If this is left out, the
980 name of the compilation function will be used.
981 2. The compilation function -- a Python function (not the name of the
982 function as a string).
984 As with filter registration, it is also possible to use this as a decorator, in
985 Python 2.4 and above::
987 @register.tag(name="current_time")
988 def do_current_time(parser, token):
992 def shout(parser, token):
995 If you leave off the ``name`` argument, as in the second example above, Django
996 will use the function's name as the tag name.
998 Passing template variables to the tag
999 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1001 Although you can pass any number of arguments to a template tag using
1002 ``token.split_contents()``, the arguments are all unpacked as
1003 string literals. A little more work is required in order to dynamic content (a
1004 template variable) to a template tag as an argument.
1006 While the previous examples have formatted the current time into a string and
1007 returned the string, suppose you wanted to pass in a ``DateTimeField`` from an
1008 object and have the template tag format that date-time::
1010 <p>This post was last updated at {% format_time blog_entry.date_updated "%Y-%m-%d %I:%M %p" %}.</p>
1012 Initially, ``token.split_contents()`` will return three values:
1014 1. The tag name ``format_time``.
1015 2. The string "blog_entry.date_updated" (without the surrounding quotes).
1016 3. The formatting string "%Y-%m-%d %I:%M %p". The return value from
1017 ``split_contents()`` will include the leading and trailing quotes for
1018 string literals like this.
1020 Now your tag should begin to look like this::
1022 from django import template
1023 def do_format_time(parser, token):
1025 # split_contents() knows not to split quoted strings.
1026 tag_name, date_to_be_formatted, format_string = token.split_contents()
1028 raise template.TemplateSyntaxError, "%r tag requires exactly two arguments" % token.contents.split()[0]
1029 if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")):
1030 raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
1031 return FormatTimeNode(date_to_be_formatted, format_string[1:-1])
1033 You also have to change the renderer to retrieve the actual contents of the
1034 ``date_updated`` property of the ``blog_entry`` object. This can be
1035 accomplished by using the ``resolve_variable()`` function in
1036 ``django.template``. You pass ``resolve_variable()`` the variable name and the
1037 current context, available in the ``render`` method::
1039 from django import template
1040 from django.template import resolve_variable
1042 class FormatTimeNode(template.Node):
1043 def __init__(self, date_to_be_formatted, format_string):
1044 self.date_to_be_formatted = date_to_be_formatted
1045 self.format_string = format_string
1047 def render(self, context):
1049 actual_date = resolve_variable(self.date_to_be_formatted, context)
1050 return actual_date.strftime(self.format_string)
1051 except template.VariableDoesNotExist:
1054 ``resolve_variable`` will try to resolve ``blog_entry.date_updated`` and then
1055 format it accordingly.
1057 .. admonition:: New in development version:
1059 Variable resolution has changed in the development version of Django.
1060 ``template.resolve_variable()`` is still available, but has been deprecated
1061 in favor of a new ``template.Variable`` class. Using this class will usually
1062 be more efficient than calling ``template.resolve_variable``
1064 To use the ``Variable`` class, simply instantiate it with the name of the
1065 variable to be resolved, and then call ``variable.resolve(context)``. So,
1066 in the development version, the above example would be more correctly
1071 class FormatTimeNode(template.Node):
1072 def __init__(self, date_to_be_formatted, format_string):
1073 self.date_to_be_formatted = **Variable(date_to_be_formatted)**
1074 self.format_string = format_string
1076 def render(self, context):
1078 actual_date = **self.date_to_be_formatted.resolve(context)**
1079 return actual_date.strftime(self.format_string)
1080 except template.VariableDoesNotExist:
1083 Changes are highlighted in bold.
1085 Variable resolution will throw a ``VariableDoesNotExist`` exception if it cannot
1086 resolve the string passed to it in the current context of the page.
1088 Shortcut for simple tags
1089 ~~~~~~~~~~~~~~~~~~~~~~~~
1091 Many template tags take a number of arguments -- strings or a template variables
1092 -- and return a string after doing some processing based solely on
1093 the input argument and some external information. For example, the
1094 ``current_time`` tag we wrote above is of this variety: we give it a format
1095 string, it returns the time as a string.
1097 To ease the creation of the types of tags, Django provides a helper function,
1098 ``simple_tag``. This function, which is a method of
1099 ``django.template.Library``, takes a function that accepts any number of
1100 arguments, wraps it in a ``render`` function and the other necessary bits
1101 mentioned above and registers it with the template system.
1103 Our earlier ``current_time`` function could thus be written like this::
1105 def current_time(format_string):
1106 return datetime.datetime.now().strftime(format_string)
1108 register.simple_tag(current_time)
1110 In Python 2.4, the decorator syntax also works::
1112 @register.simple_tag
1113 def current_time(token):
1116 A couple of things to note about the ``simple_tag`` helper function:
1117 * Checking for the required number of arguments, etc, has already been
1118 done by the time our function is called, so we don't need to do that.
1119 * The quotes around the argument (if any) have already been stripped away,
1120 so we just receive a plain string.
1121 * If the argument was a template variable, our function is passed the
1122 current value of the variable, not the variable itself.
1124 When your template tag does not need access to the current context, writing a
1125 function to work with the input values and using the ``simple_tag`` helper is
1126 the easiest way to create a new tag.
1131 Another common type of template tag is the type that displays some data by
1132 rendering *another* template. For example, Django's admin interface uses custom
1133 template tags to display the buttons along the bottom of the "add/change" form
1134 pages. Those buttons always look the same, but the link targets change depending
1135 on the object being edited -- so they're a perfect case for using a small
1136 template that is filled with details from the current object. (In the admin's
1137 case, this is the ``submit_row`` tag.)
1139 These sorts of tags are called `inclusion tags`.
1141 Writing inclusion tags is probably best demonstrated by example. Let's write a
1142 tag that outputs a list of choices for a given ``Poll`` object, such as was
1143 created in the tutorials_. We'll use the tag like this::
1145 {% show_results poll %}
1147 ...and the output will be something like this::
1150 <li>First choice</li>
1151 <li>Second choice</li>
1152 <li>Third choice</li>
1155 First, define the function that takes the argument and produces a dictionary of
1156 data for the result. The important point here is we only need to return a
1157 dictionary, not anything more complex. This will be used as a template context
1158 for the template fragment. Example::
1160 def show_results(poll):
1161 choices = poll.choice_set.all()
1162 return {'choices': choices}
1164 Next, create the template used to render the tag's output. This template is a
1165 fixed feature of the tag: the tag writer specifies it, not the template
1166 designer. Following our example, the template is very simple::
1169 {% for choice in choices %}
1170 <li> {{ choice }} </li>
1174 Now, create and register the inclusion tag by calling the ``inclusion_tag()``
1175 method on a ``Library`` object. Following our example, if the above template is
1176 in a file called ``results.html`` in a directory that's searched by the template
1177 loader, we'd register the tag like this::
1179 # Here, register is a django.template.Library instance, as before
1180 register.inclusion_tag('results.html')(show_results)
1182 As always, Python 2.4 decorator syntax works as well, so we could have
1185 @register.inclusion_tag('results.html')
1186 def show_results(poll):
1189 ...when first creating the function.
1191 Sometimes, your inclusion tags might require a large number of arguments,
1192 making it a pain for template authors to pass in all the arguments and remember
1193 their order. To solve this, Django provides a ``takes_context`` option for
1194 inclusion tags. If you specify ``takes_context`` in creating a template tag,
1195 the tag will have no required arguments, and the underlying Python function
1196 will have one argument -- the template context as of when the tag was called.
1198 For example, say you're writing an inclusion tag that will always be used in a
1199 context that contains ``home_link`` and ``home_title`` variables that point
1200 back to the main page. Here's what the Python function would look like::
1202 # The first argument *must* be called "context" here.
1203 def jump_link(context):
1205 'link': context['home_link'],
1206 'title': context['home_title'],
1208 # Register the custom tag as an inclusion tag with takes_context=True.
1209 register.inclusion_tag('link.html', takes_context=True)(jump_link)
1211 (Note that the first parameter to the function *must* be called ``context``.)
1213 In that ``register.inclusion_tag()`` line, we specified ``takes_context=True``
1214 and the name of the template. Here's what the template ``link.html`` might look
1217 Jump directly to <a href="{{ link }}">{{ title }}</a>.
1219 Then, any time you want to use that custom tag, load its library and call it
1220 without any arguments, like so::
1224 Note that when you're using ``takes_context=True``, there's no need to pass
1225 arguments to the template tag. It automatically gets access to the context.
1227 The ``takes_context`` parameter defaults to ``False``. When it's set to *True*,
1228 the tag is passed the context object, as in this example. That's the only
1229 difference between this case and the previous ``inclusion_tag`` example.
1231 .. _tutorials: ../tutorial01/#creating-models
1233 Setting a variable in the context
1234 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1236 The above example simply output a value. Generally, it's more flexible if your
1237 template tags set template variables instead of outputting values. That way,
1238 template authors can reuse the values that your template tags create.
1240 To set a variable in the context, just use dictionary assignment on the context
1241 object in the ``render()`` method. Here's an updated version of
1242 ``CurrentTimeNode`` that sets a template variable ``current_time`` instead of
1245 class CurrentTimeNode2(template.Node):
1246 def __init__(self, format_string):
1247 self.format_string = format_string
1248 def render(self, context):
1249 context['current_time'] = datetime.datetime.now().strftime(self.format_string)
1252 Note that ``render()`` returns the empty string. ``render()`` should always
1253 return string output. If all the template tag does is set a variable,
1254 ``render()`` should return the empty string.
1256 Here's how you'd use this new version of the tag::
1258 {% current_time "%Y-%M-%d %I:%M %p" %}<p>The time is {{ current_time }}.</p>
1260 But, there's a problem with ``CurrentTimeNode2``: The variable name
1261 ``current_time`` is hard-coded. This means you'll need to make sure your
1262 template doesn't use ``{{ current_time }}`` anywhere else, because the
1263 ``{% current_time %}`` will blindly overwrite that variable's value. A cleaner
1264 solution is to make the template tag specify the name of the output variable,
1267 {% get_current_time "%Y-%M-%d %I:%M %p" as my_current_time %}
1268 <p>The current time is {{ my_current_time }}.</p>
1270 To do that, you'll need to refactor both the compilation function and ``Node``
1273 class CurrentTimeNode3(template.Node):
1274 def __init__(self, format_string, var_name):
1275 self.format_string = format_string
1276 self.var_name = var_name
1277 def render(self, context):
1278 context[self.var_name] = datetime.datetime.now().strftime(self.format_string)
1282 def do_current_time(parser, token):
1283 # This version uses a regular expression to parse tag contents.
1285 # Splitting by None == splitting by spaces.
1286 tag_name, arg = token.contents.split(None, 1)
1288 raise template.TemplateSyntaxError, "%r tag requires arguments" % token.contents.split()[0]
1289 m = re.search(r'(.*?) as (\w+)', arg)
1291 raise template.TemplateSyntaxError, "%r tag had invalid arguments" % tag_name
1292 format_string, var_name = m.groups()
1293 if not (format_string[0] == format_string[-1] and format_string[0] in ('"', "'")):
1294 raise template.TemplateSyntaxError, "%r tag's argument should be in quotes" % tag_name
1295 return CurrentTimeNode3(format_string[1:-1], var_name)
1297 The difference here is that ``do_current_time()`` grabs the format string and
1298 the variable name, passing both to ``CurrentTimeNode3``.
1300 Parsing until another block tag
1301 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1303 Template tags can work in tandem. For instance, the standard ``{% comment %}``
1304 tag hides everything until ``{% endcomment %}``. To create a template tag such
1305 as this, use ``parser.parse()`` in your compilation function.
1307 Here's how the standard ``{% comment %}`` tag is implemented::
1309 def do_comment(parser, token):
1310 nodelist = parser.parse(('endcomment',))
1311 parser.delete_first_token()
1312 return CommentNode()
1314 class CommentNode(template.Node):
1315 def render(self, context):
1318 ``parser.parse()`` takes a tuple of names of block tags ''to parse until''. It
1319 returns an instance of ``django.template.NodeList``, which is a list of
1320 all ``Node`` objects that the parser encountered ''before'' it encountered
1321 any of the tags named in the tuple.
1323 In ``"nodelist = parser.parse(('endcomment',))"`` in the above example,
1324 ``nodelist`` is a list of all nodes between the ``{% comment %}`` and
1325 ``{% endcomment %}``, not counting ``{% comment %}`` and ``{% endcomment %}``
1328 After ``parser.parse()`` is called, the parser hasn't yet "consumed" the
1329 ``{% endcomment %}`` tag, so the code needs to explicitly call
1330 ``parser.delete_first_token()``.
1332 ``CommentNode.render()`` simply returns an empty string. Anything between
1333 ``{% comment %}`` and ``{% endcomment %}`` is ignored.
1335 Parsing until another block tag, and saving contents
1336 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1338 In the previous example, ``do_comment()`` discarded everything between
1339 ``{% comment %}`` and ``{% endcomment %}``. Instead of doing that, it's
1340 possible to do something with the code between block tags.
1342 For example, here's a custom template tag, ``{% upper %}``, that capitalizes
1343 everything between itself and ``{% endupper %}``.
1347 {% upper %}This will appear in uppercase, {{ your_name }}.{% endupper %}
1349 As in the previous example, we'll use ``parser.parse()``. But this time, we
1350 pass the resulting ``nodelist`` to the ``Node``::
1352 def do_upper(parser, token):
1353 nodelist = parser.parse(('endupper',))
1354 parser.delete_first_token()
1355 return UpperNode(nodelist)
1357 class UpperNode(template.Node):
1358 def __init__(self, nodelist):
1359 self.nodelist = nodelist
1360 def render(self, context):
1361 output = self.nodelist.render(context)
1362 return output.upper()
1364 The only new concept here is the ``self.nodelist.render(context)`` in
1365 ``UpperNode.render()``.
1367 For more examples of complex rendering, see the source code for ``{% if %}``,
1368 ``{% for %}``, ``{% ifequal %}`` and ``{% ifchanged %}``. They live in
1369 ``django/template/defaulttags.py``.
1373 Configuring the template system in standalone mode
1374 ==================================================
1378 This section is only of interest to people trying to use the template
1379 system as an output component in another application. If you're using the
1380 template system as part of a Django application, nothing here applies to
1383 Normally, Django will load all the configuration information it needs from its
1384 own default configuration file, combined with the settings in the module given
1385 in the ``DJANGO_SETTINGS_MODULE`` environment variable. But if you're using the
1386 template system independently of the rest of Django, the environment variable
1387 approach isn't very convenient, because you probably want to configure the
1388 template system in line with the rest of your application rather than dealing
1389 with settings files and pointing to them via environment variables.
1391 To solve this problem, you need to use the manual configuration option
1392 described in the `settings file`_ documentation. Simply import the appropriate
1393 pieces of the templating system and then, *before* you call any of the
1394 templating functions, call ``django.conf.settings.configure()`` with any
1395 settings you wish to specify. You might want to consider setting at least
1396 ``TEMPLATE_DIRS`` (if you're going to use template loaders),
1397 ``DEFAULT_CHARSET`` (although the default of ``utf-8`` is probably fine) and
1398 ``TEMPLATE_DEBUG``. All available settings are described in the
1399 `settings documentation`_, and any setting starting with *TEMPLATE_*
1400 is of obvious interest.
1402 .. _settings file: ../settings/#using-settings-without-the-django-settings-module-environment-variable
1403 .. _settings documentation: ../settings/