|
1 ==================================================== |
|
2 The Django template language: For Python programmers |
|
3 ==================================================== |
|
4 |
|
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 :doc:`/topics/templates`. |
|
8 |
|
9 If you're looking to use the Django template system as part of another |
|
10 application -- i.e., without the rest of the framework -- make sure to read |
|
11 the `configuration`_ section later in this document. |
|
12 |
|
13 .. _configuration: `configuring the template system in standalone mode`_ |
|
14 |
|
15 Basics |
|
16 ====== |
|
17 |
|
18 A **template** is a text document, or a normal Python string, that is marked-up |
|
19 using the Django template language. A template can contain **block tags** or |
|
20 **variables**. |
|
21 |
|
22 A **block tag** is a symbol within a template that does something. |
|
23 |
|
24 This definition is deliberately vague. For example, a block tag can output |
|
25 content, serve as a control structure (an "if" statement or "for" loop), grab |
|
26 content from a database or enable access to other template tags. |
|
27 |
|
28 Block tags are surrounded by ``"{%"`` and ``"%}"``. |
|
29 |
|
30 Example template with block tags: |
|
31 |
|
32 .. code-block:: html+django |
|
33 |
|
34 {% if is_logged_in %}Thanks for logging in!{% else %}Please log in.{% endif %} |
|
35 |
|
36 A **variable** is a symbol within a template that outputs a value. |
|
37 |
|
38 Variable tags are surrounded by ``"{{"`` and ``"}}"``. |
|
39 |
|
40 Example template with variables: |
|
41 |
|
42 .. code-block:: html+django |
|
43 |
|
44 My first name is {{ first_name }}. My last name is {{ last_name }}. |
|
45 |
|
46 A **context** is a "variable name" -> "variable value" mapping that is passed |
|
47 to a template. |
|
48 |
|
49 A template **renders** a context by replacing the variable "holes" with values |
|
50 from the context and executing all block tags. |
|
51 |
|
52 Using the template system |
|
53 ========================= |
|
54 |
|
55 .. class:: django.template.Template |
|
56 |
|
57 Using the template system in Python is a two-step process: |
|
58 |
|
59 * First, you compile the raw template code into a ``Template`` object. |
|
60 * Then, you call the ``render()`` method of the ``Template`` object with a |
|
61 given context. |
|
62 |
|
63 Compiling a string |
|
64 ------------------ |
|
65 |
|
66 The easiest way to create a ``Template`` object is by instantiating it |
|
67 directly. The class lives at :class:`django.template.Template`. The constructor |
|
68 takes one argument -- the raw template code:: |
|
69 |
|
70 >>> from django.template import Template |
|
71 >>> t = Template("My name is {{ my_name }}.") |
|
72 >>> print t |
|
73 <django.template.Template instance> |
|
74 |
|
75 .. admonition:: Behind the scenes |
|
76 |
|
77 The system only parses your raw template code once -- when you create the |
|
78 ``Template`` object. From then on, it's stored internally as a "node" |
|
79 structure for performance. |
|
80 |
|
81 Even the parsing itself is quite fast. Most of the parsing happens via a |
|
82 single call to a single, short, regular expression. |
|
83 |
|
84 Rendering a context |
|
85 ------------------- |
|
86 |
|
87 .. method:: render(context) |
|
88 |
|
89 Once you have a compiled ``Template`` object, you can render a context -- or |
|
90 multiple contexts -- with it. The ``Context`` class lives at |
|
91 :class:`django.template.Context`, and the constructor takes two (optional) |
|
92 arguments: |
|
93 |
|
94 * A dictionary mapping variable names to variable values. |
|
95 |
|
96 * The name of the current application. This application name is used |
|
97 to help :ref:`resolve namespaced URLs<topics-http-reversing-url-namespaces>`. |
|
98 If you're not using namespaced URLs, you can ignore this argument. |
|
99 |
|
100 Call the ``Template`` object's ``render()`` method with the context to "fill" the |
|
101 template:: |
|
102 |
|
103 >>> from django.template import Context, Template |
|
104 >>> t = Template("My name is {{ my_name }}.") |
|
105 |
|
106 >>> c = Context({"my_name": "Adrian"}) |
|
107 >>> t.render(c) |
|
108 "My name is Adrian." |
|
109 |
|
110 >>> c = Context({"my_name": "Dolores"}) |
|
111 >>> t.render(c) |
|
112 "My name is Dolores." |
|
113 |
|
114 Variable names must consist of any letter (A-Z), any digit (0-9), an underscore |
|
115 or a dot. |
|
116 |
|
117 Dots have a special meaning in template rendering. A dot in a variable name |
|
118 signifies **lookup**. Specifically, when the template system encounters a dot |
|
119 in a variable name, it tries the following lookups, in this order: |
|
120 |
|
121 * Dictionary lookup. Example: ``foo["bar"]`` |
|
122 * Attribute lookup. Example: ``foo.bar`` |
|
123 * Method call. Example: ``foo.bar()`` |
|
124 * List-index lookup. Example: ``foo[bar]`` |
|
125 |
|
126 The template system uses the first lookup type that works. It's short-circuit |
|
127 logic. |
|
128 |
|
129 Here are a few examples:: |
|
130 |
|
131 >>> from django.template import Context, Template |
|
132 >>> t = Template("My name is {{ person.first_name }}.") |
|
133 >>> d = {"person": {"first_name": "Joe", "last_name": "Johnson"}} |
|
134 >>> t.render(Context(d)) |
|
135 "My name is Joe." |
|
136 |
|
137 >>> class PersonClass: pass |
|
138 >>> p = PersonClass() |
|
139 >>> p.first_name = "Ron" |
|
140 >>> p.last_name = "Nasty" |
|
141 >>> t.render(Context({"person": p})) |
|
142 "My name is Ron." |
|
143 |
|
144 >>> class PersonClass2: |
|
145 ... def first_name(self): |
|
146 ... return "Samantha" |
|
147 >>> p = PersonClass2() |
|
148 >>> t.render(Context({"person": p})) |
|
149 "My name is Samantha." |
|
150 |
|
151 >>> t = Template("The first stooge in the list is {{ stooges.0 }}.") |
|
152 >>> c = Context({"stooges": ["Larry", "Curly", "Moe"]}) |
|
153 >>> t.render(c) |
|
154 "The first stooge in the list is Larry." |
|
155 |
|
156 Method lookups are slightly more complex than the other lookup types. Here are |
|
157 some things to keep in mind: |
|
158 |
|
159 * If, during the method lookup, a method raises an exception, the exception |
|
160 will be propagated, unless the exception has an attribute |
|
161 ``silent_variable_failure`` whose value is ``True``. If the exception |
|
162 *does* have a ``silent_variable_failure`` attribute, the variable will |
|
163 render as an empty string. Example:: |
|
164 |
|
165 >>> t = Template("My name is {{ person.first_name }}.") |
|
166 >>> class PersonClass3: |
|
167 ... def first_name(self): |
|
168 ... raise AssertionError, "foo" |
|
169 >>> p = PersonClass3() |
|
170 >>> t.render(Context({"person": p})) |
|
171 Traceback (most recent call last): |
|
172 ... |
|
173 AssertionError: foo |
|
174 |
|
175 >>> class SilentAssertionError(Exception): |
|
176 ... silent_variable_failure = True |
|
177 >>> class PersonClass4: |
|
178 ... def first_name(self): |
|
179 ... raise SilentAssertionError |
|
180 >>> p = PersonClass4() |
|
181 >>> t.render(Context({"person": p})) |
|
182 "My name is ." |
|
183 |
|
184 Note that :exc:`django.core.exceptions.ObjectDoesNotExist`, which is the |
|
185 base class for all Django database API ``DoesNotExist`` exceptions, has |
|
186 ``silent_variable_failure = True``. So if you're using Django templates |
|
187 with Django model objects, any ``DoesNotExist`` exception will fail |
|
188 silently. |
|
189 |
|
190 * A method call will only work if the method has no required arguments. |
|
191 Otherwise, the system will move to the next lookup type (list-index |
|
192 lookup). |
|
193 |
|
194 * Obviously, some methods have side effects, and it'd be either foolish or |
|
195 a security hole to allow the template system to access them. |
|
196 |
|
197 A good example is the :meth:`~django.db.models.Model.delete` method on |
|
198 each Django model object. The template system shouldn't be allowed to do |
|
199 something like this:: |
|
200 |
|
201 I will now delete this valuable data. {{ data.delete }} |
|
202 |
|
203 To prevent this, set a function attribute ``alters_data`` on the method. |
|
204 The template system won't execute a method if the method has |
|
205 ``alters_data=True`` set. The dynamically-generated |
|
206 :meth:`~django.db.models.Model.delete` and |
|
207 :meth:`~django.db.models.Model.save` methods on Django model objects get |
|
208 ``alters_data=True`` automatically. Example:: |
|
209 |
|
210 def sensitive_function(self): |
|
211 self.database_record.delete() |
|
212 sensitive_function.alters_data = True |
|
213 |
|
214 .. _invalid-template-variables: |
|
215 |
|
216 How invalid variables are handled |
|
217 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
218 |
|
219 Generally, if a variable doesn't exist, the template system inserts the |
|
220 value of the :setting:`TEMPLATE_STRING_IF_INVALID` setting, which is set to |
|
221 ``''`` (the empty string) by default. |
|
222 |
|
223 Filters that are applied to an invalid variable will only be applied if |
|
224 :setting:`TEMPLATE_STRING_IF_INVALID` is set to ``''`` (the empty string). If |
|
225 :setting:`TEMPLATE_STRING_IF_INVALID` is set to any other value, variable |
|
226 filters will be ignored. |
|
227 |
|
228 This behavior is slightly different for the ``if``, ``for`` and ``regroup`` |
|
229 template tags. If an invalid variable is provided to one of these template |
|
230 tags, the variable will be interpreted as ``None``. Filters are always |
|
231 applied to invalid variables within these template tags. |
|
232 |
|
233 If :setting:`TEMPLATE_STRING_IF_INVALID` contains a ``'%s'``, the format marker will |
|
234 be replaced with the name of the invalid variable. |
|
235 |
|
236 .. admonition:: For debug purposes only! |
|
237 |
|
238 While :setting:`TEMPLATE_STRING_IF_INVALID` can be a useful debugging tool, |
|
239 it is a bad idea to turn it on as a 'development default'. |
|
240 |
|
241 Many templates, including those in the Admin site, rely upon the |
|
242 silence of the template system when a non-existent variable is |
|
243 encountered. If you assign a value other than ``''`` to |
|
244 :setting:`TEMPLATE_STRING_IF_INVALID`, you will experience rendering |
|
245 problems with these templates and sites. |
|
246 |
|
247 Generally, :setting:`TEMPLATE_STRING_IF_INVALID` should only be enabled |
|
248 in order to debug a specific template problem, then cleared |
|
249 once debugging is complete. |
|
250 |
|
251 Playing with Context objects |
|
252 ---------------------------- |
|
253 |
|
254 .. class:: django.template.Context |
|
255 |
|
256 Most of the time, you'll instantiate ``Context`` objects by passing in a |
|
257 fully-populated dictionary to ``Context()``. But you can add and delete items |
|
258 from a ``Context`` object once it's been instantiated, too, using standard |
|
259 dictionary syntax:: |
|
260 |
|
261 >>> c = Context({"foo": "bar"}) |
|
262 >>> c['foo'] |
|
263 'bar' |
|
264 >>> del c['foo'] |
|
265 >>> c['foo'] |
|
266 '' |
|
267 >>> c['newvariable'] = 'hello' |
|
268 >>> c['newvariable'] |
|
269 'hello' |
|
270 |
|
271 .. method:: pop() |
|
272 .. method:: push() |
|
273 .. exception:: django.template.ContextPopException |
|
274 |
|
275 A ``Context`` object is a stack. That is, you can ``push()`` and ``pop()`` it. |
|
276 If you ``pop()`` too much, it'll raise |
|
277 ``django.template.ContextPopException``:: |
|
278 |
|
279 >>> c = Context() |
|
280 >>> c['foo'] = 'first level' |
|
281 >>> c.push() |
|
282 >>> c['foo'] = 'second level' |
|
283 >>> c['foo'] |
|
284 'second level' |
|
285 >>> c.pop() |
|
286 >>> c['foo'] |
|
287 'first level' |
|
288 >>> c['foo'] = 'overwritten' |
|
289 >>> c['foo'] |
|
290 'overwritten' |
|
291 >>> c.pop() |
|
292 Traceback (most recent call last): |
|
293 ... |
|
294 django.template.ContextPopException |
|
295 |
|
296 .. method:: update(other_dict) |
|
297 |
|
298 In addition to ``push()`` and ``pop()``, the ``Context`` |
|
299 object also defines an ``update()`` method. This works like ``push()`` |
|
300 but takes a dictionary as an argument and pushes that dictionary onto |
|
301 the stack instead of an empty one. |
|
302 |
|
303 >>> c = Context() |
|
304 >>> c['foo'] = 'first level' |
|
305 >>> c.update({'foo': 'updated'}) |
|
306 {'foo': 'updated'} |
|
307 >>> c['foo'] |
|
308 'updated' |
|
309 >>> c.pop() |
|
310 {'foo': 'updated'} |
|
311 >>> c['foo'] |
|
312 'first level' |
|
313 |
|
314 Using a ``Context`` as a stack comes in handy in some custom template tags, as |
|
315 you'll see below. |
|
316 |
|
317 .. _subclassing-context-requestcontext: |
|
318 |
|
319 Subclassing Context: RequestContext |
|
320 ----------------------------------- |
|
321 |
|
322 Django comes with a special ``Context`` class, |
|
323 ``django.template.RequestContext``, that acts slightly differently than the |
|
324 normal ``django.template.Context``. The first difference is that it takes an |
|
325 :class:`~django.http.HttpRequest` as its first argument. For example:: |
|
326 |
|
327 c = RequestContext(request, { |
|
328 'foo': 'bar', |
|
329 }) |
|
330 |
|
331 The second difference is that it automatically populates the context with a few |
|
332 variables, according to your :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting. |
|
333 |
|
334 The :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting is a tuple of callables -- |
|
335 called **context processors** -- that take a request object as their argument |
|
336 and return a dictionary of items to be merged into the context. By default, |
|
337 :setting:`TEMPLATE_CONTEXT_PROCESSORS` is set to:: |
|
338 |
|
339 ("django.contrib.auth.context_processors.auth", |
|
340 "django.core.context_processors.debug", |
|
341 "django.core.context_processors.i18n", |
|
342 "django.core.context_processors.media", |
|
343 "django.contrib.messages.context_processors.messages") |
|
344 |
|
345 .. versionadded:: 1.2 |
|
346 In addition to these, ``RequestContext`` always uses |
|
347 ``django.core.context_processors.csrf``. This is a security |
|
348 related context processor required by the admin and other contrib apps, and, |
|
349 in case of accidental misconfiguration, it is deliberately hardcoded in and |
|
350 cannot be turned off by the :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting. |
|
351 |
|
352 .. versionadded:: 1.2 |
|
353 The ``'messages'`` context processor was added. For more information, see |
|
354 the :doc:`messages documentation </ref/contrib/messages>`. |
|
355 |
|
356 .. versionchanged:: 1.2 |
|
357 The auth context processor was moved in this release from its old location |
|
358 ``django.core.context_processors.auth`` to |
|
359 ``django.contrib.auth.context_processors.auth``. |
|
360 |
|
361 Each processor is applied in order. That means, if one processor adds a |
|
362 variable to the context and a second processor adds a variable with the same |
|
363 name, the second will override the first. The default processors are explained |
|
364 below. |
|
365 |
|
366 .. admonition:: When context processors are applied |
|
367 |
|
368 When you use ``RequestContext``, the variables you supply directly |
|
369 are added first, followed any variables supplied by context |
|
370 processors. This means that a context processor may overwrite a |
|
371 variable you've supplied, so take care to avoid variable names |
|
372 which overlap with those supplied by your context processors. |
|
373 |
|
374 Also, you can give ``RequestContext`` a list of additional processors, using the |
|
375 optional, third positional argument, ``processors``. In this example, the |
|
376 ``RequestContext`` instance gets a ``ip_address`` variable:: |
|
377 |
|
378 def ip_address_processor(request): |
|
379 return {'ip_address': request.META['REMOTE_ADDR']} |
|
380 |
|
381 def some_view(request): |
|
382 # ... |
|
383 c = RequestContext(request, { |
|
384 'foo': 'bar', |
|
385 }, [ip_address_processor]) |
|
386 return HttpResponse(t.render(c)) |
|
387 |
|
388 .. note:: |
|
389 If you're using Django's ``render_to_response()`` shortcut to populate a |
|
390 template with the contents of a dictionary, your template will be passed a |
|
391 ``Context`` instance by default (not a ``RequestContext``). To use a |
|
392 ``RequestContext`` in your template rendering, pass an optional third |
|
393 argument to ``render_to_response()``: a ``RequestContext`` |
|
394 instance. Your code might look like this:: |
|
395 |
|
396 def some_view(request): |
|
397 # ... |
|
398 return render_to_response('my_template.html', |
|
399 my_data_dictionary, |
|
400 context_instance=RequestContext(request)) |
|
401 |
|
402 Here's what each of the default processors does: |
|
403 |
|
404 django.contrib.auth.context_processors.auth |
|
405 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
406 |
|
407 If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every |
|
408 ``RequestContext`` will contain these three variables: |
|
409 |
|
410 * ``user`` -- An ``auth.User`` instance representing the currently |
|
411 logged-in user (or an ``AnonymousUser`` instance, if the client isn't |
|
412 logged in). |
|
413 |
|
414 * ``messages`` -- A list of messages (as strings) that have been set |
|
415 via the :doc:`messages framework </ref/contrib/messages>`. |
|
416 |
|
417 * ``perms`` -- An instance of |
|
418 ``django.core.context_processors.PermWrapper``, representing the |
|
419 permissions that the currently logged-in user has. |
|
420 |
|
421 .. versionchanged:: 1.2 |
|
422 This context processor was moved in this release from |
|
423 ``django.core.context_processors.auth`` to its current location. |
|
424 |
|
425 .. versionchanged:: 1.2 |
|
426 Prior to version 1.2, the ``messages`` variable was a lazy accessor for |
|
427 ``user.get_and_delete_messages()``. It has been changed to include any |
|
428 messages added via the :doc:`messages framework </ref/contrib/messages>`. |
|
429 |
|
430 django.core.context_processors.debug |
|
431 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
432 |
|
433 If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every |
|
434 ``RequestContext`` will contain these two variables -- but only if your |
|
435 :setting:`DEBUG` setting is set to ``True`` and the request's IP address |
|
436 (``request.META['REMOTE_ADDR']``) is in the :setting:`INTERNAL_IPS` setting: |
|
437 |
|
438 * ``debug`` -- ``True``. You can use this in templates to test whether |
|
439 you're in :setting:`DEBUG` mode. |
|
440 * ``sql_queries`` -- A list of ``{'sql': ..., 'time': ...}`` dictionaries, |
|
441 representing every SQL query that has happened so far during the request |
|
442 and how long it took. The list is in order by query. |
|
443 |
|
444 django.core.context_processors.i18n |
|
445 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
446 |
|
447 If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every |
|
448 ``RequestContext`` will contain these two variables: |
|
449 |
|
450 * ``LANGUAGES`` -- The value of the :setting:`LANGUAGES` setting. |
|
451 * ``LANGUAGE_CODE`` -- ``request.LANGUAGE_CODE``, if it exists. Otherwise, |
|
452 the value of the :setting:`LANGUAGE_CODE` setting. |
|
453 |
|
454 See :doc:`/topics/i18n/index` for more. |
|
455 |
|
456 django.core.context_processors.media |
|
457 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
458 |
|
459 .. versionadded:: 1.0 |
|
460 |
|
461 If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every |
|
462 ``RequestContext`` will contain a variable ``MEDIA_URL``, providing the |
|
463 value of the :setting:`MEDIA_URL` setting. |
|
464 |
|
465 django.core.context_processors.csrf |
|
466 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
467 |
|
468 .. versionadded:: 1.2 |
|
469 |
|
470 This processor adds a token that is needed by the ``csrf_token`` template tag |
|
471 for protection against :doc:`Cross Site Request Forgeries </ref/contrib/csrf>`. |
|
472 |
|
473 django.core.context_processors.request |
|
474 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
475 |
|
476 If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every |
|
477 ``RequestContext`` will contain a variable ``request``, which is the current |
|
478 :class:`~django.http.HttpRequest`. Note that this processor is not enabled by default; |
|
479 you'll have to activate it. |
|
480 |
|
481 django.contrib.messages.context_processors.messages |
|
482 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
483 |
|
484 If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every |
|
485 ``RequestContext`` will contain a single additional variable: |
|
486 |
|
487 * ``messages`` -- A list of messages (as strings) that have been set |
|
488 via the user model (using ``user.message_set.create``) or through |
|
489 the :doc:`messages framework </ref/contrib/messages>`. |
|
490 |
|
491 .. versionadded:: 1.2 |
|
492 This template context variable was previously supplied by the ``'auth'`` |
|
493 context processor. For backwards compatibility the ``'auth'`` context |
|
494 processor will continue to supply the ``messages`` variable until Django |
|
495 1.4. If you use the ``messages`` variable, your project will work with |
|
496 either (or both) context processors, but it is recommended to add |
|
497 ``django.contrib.messages.context_processors.messages`` so your project |
|
498 will be prepared for the future upgrade. |
|
499 |
|
500 Writing your own context processors |
|
501 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
502 |
|
503 A context processor has a very simple interface: It's just a Python function |
|
504 that takes one argument, an :class:`~django.http.HttpRequest` object, and |
|
505 returns a dictionary that gets added to the template context. Each context |
|
506 processor *must* return a dictionary. |
|
507 |
|
508 Custom context processors can live anywhere in your code base. All Django cares |
|
509 about is that your custom context processors are pointed-to by your |
|
510 :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting. |
|
511 |
|
512 Loading templates |
|
513 ----------------- |
|
514 |
|
515 Generally, you'll store templates in files on your filesystem rather than using |
|
516 the low-level ``Template`` API yourself. Save templates in a directory |
|
517 specified as a **template directory**. |
|
518 |
|
519 Django searches for template directories in a number of places, depending on |
|
520 your template-loader settings (see "Loader types" below), but the most basic |
|
521 way of specifying template directories is by using the :setting:`TEMPLATE_DIRS` |
|
522 setting. |
|
523 |
|
524 The TEMPLATE_DIRS setting |
|
525 ~~~~~~~~~~~~~~~~~~~~~~~~~ |
|
526 |
|
527 Tell Django what your template directories are by using the |
|
528 :setting:`TEMPLATE_DIRS` setting in your settings file. This should be set to a |
|
529 list or tuple of strings that contain full paths to your template |
|
530 directory(ies). Example:: |
|
531 |
|
532 TEMPLATE_DIRS = ( |
|
533 "/home/html/templates/lawrence.com", |
|
534 "/home/html/templates/default", |
|
535 ) |
|
536 |
|
537 Your templates can go anywhere you want, as long as the directories and |
|
538 templates are readable by the Web server. They can have any extension you want, |
|
539 such as ``.html`` or ``.txt``, or they can have no extension at all. |
|
540 |
|
541 Note that these paths should use Unix-style forward slashes, even on Windows. |
|
542 |
|
543 .. _ref-templates-api-the-python-api: |
|
544 |
|
545 The Python API |
|
546 ~~~~~~~~~~~~~~ |
|
547 |
|
548 Django has two ways to load templates from files: |
|
549 |
|
550 .. function:: django.template.loader.get_template(template_name) |
|
551 |
|
552 ``get_template`` returns the compiled template (a ``Template`` object) for |
|
553 the template with the given name. If the template doesn't exist, it raises |
|
554 ``django.template.TemplateDoesNotExist``. |
|
555 |
|
556 .. function:: django.template.loader.select_template(template_name_list) |
|
557 |
|
558 ``select_template`` is just like ``get_template``, except it takes a list |
|
559 of template names. Of the list, it returns the first template that exists. |
|
560 |
|
561 For example, if you call ``get_template('story_detail.html')`` and have the |
|
562 above :setting:`TEMPLATE_DIRS` setting, here are the files Django will look for, |
|
563 in order: |
|
564 |
|
565 * ``/home/html/templates/lawrence.com/story_detail.html`` |
|
566 * ``/home/html/templates/default/story_detail.html`` |
|
567 |
|
568 If you call ``select_template(['story_253_detail.html', 'story_detail.html'])``, |
|
569 here's what Django will look for: |
|
570 |
|
571 * ``/home/html/templates/lawrence.com/story_253_detail.html`` |
|
572 * ``/home/html/templates/default/story_253_detail.html`` |
|
573 * ``/home/html/templates/lawrence.com/story_detail.html`` |
|
574 * ``/home/html/templates/default/story_detail.html`` |
|
575 |
|
576 When Django finds a template that exists, it stops looking. |
|
577 |
|
578 .. admonition:: Tip |
|
579 |
|
580 You can use ``select_template()`` for super-flexible "templatability." For |
|
581 example, if you've written a news story and want some stories to have |
|
582 custom templates, use something like |
|
583 ``select_template(['story_%s_detail.html' % story.id, 'story_detail.html'])``. |
|
584 That'll allow you to use a custom template for an individual story, with a |
|
585 fallback template for stories that don't have custom templates. |
|
586 |
|
587 Using subdirectories |
|
588 ~~~~~~~~~~~~~~~~~~~~ |
|
589 |
|
590 It's possible -- and preferable -- to organize templates in subdirectories of |
|
591 the template directory. The convention is to make a subdirectory for each |
|
592 Django app, with subdirectories within those subdirectories as needed. |
|
593 |
|
594 Do this for your own sanity. Storing all templates in the root level of a |
|
595 single directory gets messy. |
|
596 |
|
597 To load a template that's within a subdirectory, just use a slash, like so:: |
|
598 |
|
599 get_template('news/story_detail.html') |
|
600 |
|
601 Using the same :setting:`TEMPLATE_DIRS` setting from above, this example |
|
602 ``get_template()`` call will attempt to load the following templates: |
|
603 |
|
604 * ``/home/html/templates/lawrence.com/news/story_detail.html`` |
|
605 * ``/home/html/templates/default/news/story_detail.html`` |
|
606 |
|
607 .. _template-loaders: |
|
608 |
|
609 Loader types |
|
610 ~~~~~~~~~~~~ |
|
611 |
|
612 By default, Django uses a filesystem-based template loader, but Django comes |
|
613 with a few other template loaders, which know how to load templates from other |
|
614 sources. |
|
615 |
|
616 Some of these other loaders are disabled by default, but you can activate them |
|
617 by editing your :setting:`TEMPLATE_LOADERS` setting. :setting:`TEMPLATE_LOADERS` |
|
618 should be a tuple of strings, where each string represents a template loader. |
|
619 Here are the template loaders that come with Django: |
|
620 |
|
621 ``django.template.loaders.filesystem.Loader`` |
|
622 Loads templates from the filesystem, according to :setting:`TEMPLATE_DIRS`. |
|
623 This loader is enabled by default. |
|
624 |
|
625 ``django.template.loaders.app_directories.Loader`` |
|
626 Loads templates from Django apps on the filesystem. For each app in |
|
627 :setting:`INSTALLED_APPS`, the loader looks for a ``templates`` |
|
628 subdirectory. If the directory exists, Django looks for templates in there. |
|
629 |
|
630 This means you can store templates with your individual apps. This also |
|
631 makes it easy to distribute Django apps with default templates. |
|
632 |
|
633 For example, for this setting:: |
|
634 |
|
635 INSTALLED_APPS = ('myproject.polls', 'myproject.music') |
|
636 |
|
637 ...then ``get_template('foo.html')`` will look for templates in these |
|
638 directories, in this order: |
|
639 |
|
640 * ``/path/to/myproject/polls/templates/foo.html`` |
|
641 * ``/path/to/myproject/music/templates/foo.html`` |
|
642 |
|
643 Note that the loader performs an optimization when it is first imported: It |
|
644 caches a list of which :setting:`INSTALLED_APPS` packages have a |
|
645 ``templates`` subdirectory. |
|
646 |
|
647 This loader is enabled by default. |
|
648 |
|
649 ``django.template.loaders.eggs.Loader`` |
|
650 Just like ``app_directories`` above, but it loads templates from Python |
|
651 eggs rather than from the filesystem. |
|
652 |
|
653 This loader is disabled by default. |
|
654 |
|
655 ``django.template.loaders.cached.Loader`` |
|
656 By default, the templating system will read and compile your templates every |
|
657 time they need to be rendered. While the Django templating system is quite |
|
658 fast, the overhead from reading and compiling templates can add up. |
|
659 |
|
660 The cached template loader is a class-based loader that you configure with |
|
661 a list of other loaders that it should wrap. The wrapped loaders are used to |
|
662 locate unknown templates when they are first encountered. The cached loader |
|
663 then stores the compiled ``Template`` in memory. The cached ``Template`` |
|
664 instance is returned for subsequent requests to load the same template. |
|
665 |
|
666 For example, to enable template caching with the ``filesystem`` and |
|
667 ``app_directories`` template loaders you might use the following settings:: |
|
668 |
|
669 TEMPLATE_LOADERS = ( |
|
670 ('django.template.loaders.cached.Loader', ( |
|
671 'django.template.loaders.filesystem.Loader', |
|
672 'django.template.loaders.app_directories.Loader', |
|
673 )), |
|
674 ) |
|
675 |
|
676 .. note:: |
|
677 All of the built-in Django template tags are safe to use with the cached |
|
678 loader, but if you're using custom template tags that come from third |
|
679 party packages, or that you wrote yourself, you should ensure that the |
|
680 ``Node`` implementation for each tag is thread-safe. For more |
|
681 information, see |
|
682 :ref:`template tag thread safety considerations<template_tag_thread_safety>`. |
|
683 |
|
684 This loader is disabled by default. |
|
685 |
|
686 Django uses the template loaders in order according to the |
|
687 :setting:`TEMPLATE_LOADERS` setting. It uses each loader until a loader finds a |
|
688 match. |
|
689 |
|
690 The ``render_to_string`` shortcut |
|
691 =================================== |
|
692 |
|
693 .. function:: django.template.loader.render_to_string(template_name, dictionary=None, context_instance=None) |
|
694 |
|
695 To cut down on the repetitive nature of loading and rendering |
|
696 templates, Django provides a shortcut function which largely |
|
697 automates the process: ``render_to_string()`` in |
|
698 :mod:`django.template.loader`, which loads a template, renders it and |
|
699 returns the resulting string:: |
|
700 |
|
701 from django.template.loader import render_to_string |
|
702 rendered = render_to_string('my_template.html', { 'foo': 'bar' }) |
|
703 |
|
704 The ``render_to_string`` shortcut takes one required argument -- |
|
705 ``template_name``, which should be the name of the template to load |
|
706 and render (or a list of template names, in which case Django will use |
|
707 the first template in the list that exists) -- and two optional arguments: |
|
708 |
|
709 dictionary |
|
710 A dictionary to be used as variables and values for the |
|
711 template's context. This can also be passed as the second |
|
712 positional argument. |
|
713 |
|
714 context_instance |
|
715 An instance of ``Context`` or a subclass (e.g., an instance of |
|
716 ``RequestContext``) to use as the template's context. This can |
|
717 also be passed as the third positional argument. |
|
718 |
|
719 See also the :func:`~django.shortcuts.render_to_response()` shortcut, which |
|
720 calls ``render_to_string`` and feeds the result into an :class:`~django.http.HttpResponse` |
|
721 suitable for returning directly from a view. |
|
722 |
|
723 Configuring the template system in standalone mode |
|
724 ================================================== |
|
725 |
|
726 .. note:: |
|
727 |
|
728 This section is only of interest to people trying to use the template |
|
729 system as an output component in another application. If you're using the |
|
730 template system as part of a Django application, nothing here applies to |
|
731 you. |
|
732 |
|
733 Normally, Django will load all the configuration information it needs from its |
|
734 own default configuration file, combined with the settings in the module given |
|
735 in the :envvar:`DJANGO_SETTINGS_MODULE` environment variable. But if you're |
|
736 using the template system independently of the rest of Django, the environment |
|
737 variable approach isn't very convenient, because you probably want to configure |
|
738 the template system in line with the rest of your application rather than |
|
739 dealing with settings files and pointing to them via environment variables. |
|
740 |
|
741 To solve this problem, you need to use the manual configuration option described |
|
742 in :ref:`settings-without-django-settings-module`. Simply import the appropriate |
|
743 pieces of the templating system and then, *before* you call any of the |
|
744 templating functions, call :func:`django.conf.settings.configure()` with any |
|
745 settings you wish to specify. You might want to consider setting at least |
|
746 :setting:`TEMPLATE_DIRS` (if you're going to use template loaders), |
|
747 :setting:`DEFAULT_CHARSET` (although the default of ``utf-8`` is probably fine) |
|
748 and :setting:`TEMPLATE_DEBUG`. All available settings are described in the |
|
749 :doc:`settings documentation </ref/settings>`, and any setting starting with |
|
750 ``TEMPLATE_`` is of obvious interest. |
|
751 |
|
752 .. _topic-template-alternate-language: |
|
753 |
|
754 Using an alternative template language |
|
755 ====================================== |
|
756 |
|
757 .. versionadded:: 1.2 |
|
758 |
|
759 The Django ``Template`` and ``Loader`` classes implement a simple API for |
|
760 loading and rendering templates. By providing some simple wrapper classes that |
|
761 implement this API we can use third party template systems like `Jinja2 |
|
762 <http://jinja.pocoo.org/2/>`_ or `Cheetah <http://www.cheetahtemplate.org/>`_. This |
|
763 allows us to use third-party template libraries without giving up useful Django |
|
764 features like the Django ``Context`` object and handy shortcuts like |
|
765 ``render_to_response()``. |
|
766 |
|
767 The core component of the Django templating system is the ``Template`` class. |
|
768 This class has a very simple interface: it has a constructor that takes a single |
|
769 positional argument specifying the template string, and a ``render()`` method |
|
770 that takes a :class:`~django.template.Context` object and returns a string |
|
771 containing the rendered response. |
|
772 |
|
773 Suppose we're using a template language that defines a ``Template`` object with |
|
774 a ``render()`` method that takes a dictionary rather than a ``Context`` object. |
|
775 We can write a simple wrapper that implements the Django ``Template`` interface:: |
|
776 |
|
777 import some_template_language |
|
778 class Template(some_template_language.Template): |
|
779 def render(self, context): |
|
780 # flatten the Django Context into a single dictionary. |
|
781 context_dict = {} |
|
782 for d in context.dicts: |
|
783 context_dict.update(d) |
|
784 return super(Template, self).render(context_dict) |
|
785 |
|
786 That's all that's required to make our fictional ``Template`` class compatible |
|
787 with the Django loading and rendering system! |
|
788 |
|
789 The next step is to write a ``Loader`` class that returns instances of our custom |
|
790 template class instead of the default :class:`~django.template.Template`. Custom ``Loader`` |
|
791 classes should inherit from ``django.template.loader.BaseLoader`` and override |
|
792 the ``load_template_source()`` method, which takes a ``template_name`` argument, |
|
793 loads the template from disk (or elsewhere), and returns a tuple: |
|
794 ``(template_string, template_origin)``. |
|
795 |
|
796 The ``load_template()`` method of the ``Loader`` class retrieves the template |
|
797 string by calling ``load_template_source()``, instantiates a ``Template`` from |
|
798 the template source, and returns a tuple: ``(template, template_origin)``. Since |
|
799 this is the method that actually instantiates the ``Template``, we'll need to |
|
800 override it to use our custom template class instead. We can inherit from the |
|
801 builtin :class:`django.template.loaders.app_directories.Loader` to take advantage |
|
802 of the ``load_template_source()`` method implemented there:: |
|
803 |
|
804 from django.template.loaders import app_directories |
|
805 class Loader(app_directories.Loader): |
|
806 is_usable = True |
|
807 |
|
808 def load_template(self, template_name, template_dirs=None): |
|
809 source, origin = self.load_template_source(template_name, template_dirs) |
|
810 template = Template(source) |
|
811 return template, origin |
|
812 |
|
813 Finally, we need to modify our project settings, telling Django to use our custom |
|
814 loader. Now we can write all of our templates in our alternative template |
|
815 language while continuing to use the rest of the Django templating system. |