Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 1298 lines (955 sloc) 50.671 kb
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
1 =============================
2 Chapter 9: Advanced Templates
3 =============================
4
5 Although most of your interactions with Django's template language will be in
6 the role of template author, you may want to customize and extend the template
7 engine -- either to make it do something it doesn't already do, or to make your
8 job easier in some other way.
9
10 This chapter delves deep into the guts of Django's template system. It covers
11 what you need to know if you plan to extend the system or if you're just
12 curious about how it works. It also covers the auto-escaping feature, a
13 security measure you'll no doubt notice over time as you continue to use
14 Django.
15
16 If you're looking to use the Django template system as part of another
17 application (i.e., without the rest of the framework), make sure to read the
18 "Configuring the Template System in Standalone Mode" section later in the
19 chapter.
20
21 Template Language Review
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
22 ========================
23
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
24 First, let's quickly review a number of terms introduced in Chapter 4:
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
25
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
26 * A *template* is a text document, or a normal Python string, that is
27 marked up using the Django template language. A template can contain
28 template tags and variables.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
29
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
30 * A *template tag* is a symbol within a template that does something. This
31 definition is deliberately vague. For example, a template tag can produce
32 content, serve as a control structure (an ``if`` statement or ``for``
33 loop), grab content from a database, or enable access to other template
34 tags.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
35
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
36 Template tags are surrounded by ``{%`` and ``%}``::
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
37
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
38 {% if is_logged_in %}
39 Thanks for logging in!
40 {% else %}
41 Please log in.
42 {% endif %}
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
43
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
44 * A *variable* is a symbol within a template that outputs a value.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
45
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
46 Variable tags are surrounded by ``{{`` and ``}}``::
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
47
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
48 My first name is {{ first_name }}. My last name is {{ last_name }}.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
49
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
50 * A *context* is a name -> value mapping (similar to a Python
51 dictionary) that is passed to a template.
52
53 * A template *renders* a context by replacing the variable "holes" with
54 values from the context and executing all template tags.
55
56 For more details about the basics of these terms, refer back to Chapter 4.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
57
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
58 The rest of this chapter discusses ways of extending the template engine. First,
59 though, let's take a quick look at a few internals left out of Chapter 4 for
60 simplicity.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
61
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
62 RequestContext and Context Processors
63 =====================================
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
64
a4724d5 RaphaelKimmig replace render_to_response with render
RaphaelKimmig authored
65 When rendering a template, you need a context. This can be an instance of
66 ``django.template.Context``, but Django also comes with a subclass,
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
67 ``django.template.RequestContext``, that acts slightly differently.
68 ``RequestContext`` adds a bunch of variables to your template context by
69 default -- things like the ``HttpRequest`` object or information about the
a4724d5 RaphaelKimmig replace render_to_response with render
RaphaelKimmig authored
70 currently logged-in user. The ``render()`` shortcut creates a ``RequestContext``
71 unless it is passed a different context instance explicitly.
72
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
73
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
74 Use ``RequestContext`` when you don't want to have to specify the same set of
75 variables in a series of templates. For example, consider these two views::
76
77 from django.template import loader, Context
78
79 def view_1(request):
80 # ...
81 t = loader.get_template('template1.html')
82 c = Context({
83 'app': 'My app',
84 'user': request.user,
85 'ip_address': request.META['REMOTE_ADDR'],
86 'message': 'I am view 1.'
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
87 })
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
88 return t.render(c)
89
90 def view_2(request):
91 # ...
92 t = loader.get_template('template2.html')
93 c = Context({
94 'app': 'My app',
95 'user': request.user,
96 'ip_address': request.META['REMOTE_ADDR'],
97 'message': 'I am the second view.'
98 })
99 return t.render(c)
100
a4724d5 RaphaelKimmig replace render_to_response with render
RaphaelKimmig authored
101 (Note that we're deliberately *not* using the ``render()`` shortcut
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
102 in these examples -- we're manually loading the templates, constructing the
103 context objects and rendering the templates. We're "spelling out" all of the
104 steps for the purpose of clarity.)
105
106 Each view passes the same three variables -- ``app``, ``user`` and
107 ``ip_address`` -- to its template. Wouldn't it be nice if we could remove that
108 redundancy?
109
110 ``RequestContext`` and **context processors** were created to solve this
111 problem. Context processors let you specify a number of variables that get set
112 in each context automatically -- without you having to specify the variables in
a4724d5 RaphaelKimmig replace render_to_response with render
RaphaelKimmig authored
113 each ``render()`` call. The catch is that you have to use
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
114 ``RequestContext`` instead of ``Context`` when you render a template.
115
116 The most low-level way of using context processors is to create some processors
117 and pass them to ``RequestContext``. Here's how the above example could be
118 written with context processors::
119
120 from django.template import loader, RequestContext
121
122 def custom_proc(request):
123 "A context processor that provides 'app', 'user' and 'ip_address'."
124 return {
125 'app': 'My app',
126 'user': request.user,
127 'ip_address': request.META['REMOTE_ADDR']
128 }
129
130 def view_1(request):
131 # ...
132 t = loader.get_template('template1.html')
133 c = RequestContext(request, {'message': 'I am view 1.'},
134 processors=[custom_proc])
135 return t.render(c)
136
137 def view_2(request):
138 # ...
139 t = loader.get_template('template2.html')
140 c = RequestContext(request, {'message': 'I am the second view.'},
141 processors=[custom_proc])
142 return t.render(c)
143
144 Let's step through this code:
145
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
146 * First, we define a function ``custom_proc``. This is a context processor
147 -- it takes an ``HttpRequest`` object and returns a dictionary of
148 variables to use in the template context. That's all it does.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
149
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
150 * We've changed the two view functions to use ``RequestContext`` instead
151 of ``Context``. There are two differences in how the context is
152 constructed. One, ``RequestContext`` requires the first argument to be an
153 ``HttpRequest`` object -- the one that was passed into the view function
154 in the first place (``request``). Two, ``RequestContext`` takes an
155 optional ``processors`` argument, which is a list or tuple of context
156 processor functions to use. Here, we pass in ``custom_proc``, the custom
157 processor we defined above.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
158
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
159 * Each view no longer has to include ``app``, ``user`` or ``ip_address`` in
160 its context construction, because those are provided by ``custom_proc``.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
161
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
162 * Each view *still* has the flexibility to introduce any custom template
163 variables it might need. In this example, the ``message`` template
164 variable is set differently in each view.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
165
a4724d5 RaphaelKimmig replace render_to_response with render
RaphaelKimmig authored
166 In Chapter 4, we introduced the ``render()`` shortcut, which saves
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
167 you from having to call ``loader.get_template()``, then create a ``Context``,
168 then call the ``render()`` method on the template. In order to demonstrate the
169 lower-level workings of context processors, the above examples didn't use
a4724d5 RaphaelKimmig replace render_to_response with render
RaphaelKimmig authored
170 ``render()``, . But it's possible -- and preferable -- to use
171 context processors with ``render()``. Do this with the
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
172 ``context_instance`` argument, like so::
173
a4724d5 RaphaelKimmig replace render_to_response with render
RaphaelKimmig authored
174 from django.shortcuts import render
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
175 from django.template import RequestContext
176
177 def custom_proc(request):
178 "A context processor that provides 'app', 'user' and 'ip_address'."
179 return {
180 'app': 'My app',
181 'user': request.user,
182 'ip_address': request.META['REMOTE_ADDR']
183 }
184
185 def view_1(request):
186 # ...
a4724d5 RaphaelKimmig replace render_to_response with render
RaphaelKimmig authored
187 return render(request, 'template1.html',
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
188 {'message': 'I am view 1.'},
189 context_instance=RequestContext(request, processors=[custom_proc]))
190
191 def view_2(request):
192 # ...
a4724d5 RaphaelKimmig replace render_to_response with render
RaphaelKimmig authored
193 return render(request, 'template2.html',
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
194 {'message': 'I am the second view.'},
195 context_instance=RequestContext(request, processors=[custom_proc]))
196
197 Here, we've trimmed down each view's template rendering code to a single
198 (wrapped) line.
199
200 This is an improvement, but, evaluating the conciseness of this code, we have
201 to admit we're now almost overdosing on the *other* end of the spectrum. We've
202 removed redundancy in data (our template variables) at the cost of adding
203 redundancy in code (in the ``processors`` call). Using context processors
204 doesn't save you much typing if you have to type ``processors`` all the time.
205
206 For that reason, Django provides support for *global* context processors. The
207 ``TEMPLATE_CONTEXT_PROCESSORS`` setting (in your ``settings.py``) designates
208 which context processors should *always* be applied to ``RequestContext``. This
209 removes the need to specify ``processors`` each time you use
210 ``RequestContext``.
211
212 By default, ``TEMPLATE_CONTEXT_PROCESSORS`` is set to the following::
213
214 TEMPLATE_CONTEXT_PROCESSORS = (
215 'django.core.context_processors.auth',
216 'django.core.context_processors.debug',
217 'django.core.context_processors.i18n',
218 'django.core.context_processors.media',
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
219 )
220
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
221 This setting is a tuple of callables that use the same interface as our
222 ``custom_proc`` function above -- functions that take a request object as their
223 argument and return a dictionary of items to be merged into the context. Note
224 that the values in ``TEMPLATE_CONTEXT_PROCESSORS`` are specified as *strings*,
225 which means the processors are required to be somewhere on your Python path
226 (so you can refer to them from the setting).
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
227
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
228 Each processor is applied in order. That is, if one processor adds a variable
229 to the context and a second processor adds a variable with the same name, the
230 second will override the first.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
231
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
232 Django provides a number of simple context processors, including the ones that
233 are enabled by default:
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
234
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
235 django.core.context_processors.auth
236 -----------------------------------
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
237
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
238 If ``TEMPLATE_CONTEXT_PROCESSORS`` contains this processor, every
239 ``RequestContext`` will contain these variables:
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
240
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
241 * ``user``: A ``django.contrib.auth.models.User`` instance representing the
242 current logged-in user (or an ``AnonymousUser`` instance, if the client
243 isn't logged in).
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
244
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
245 * ``messages``: A list of messages (as strings) for the current logged-in
246 user. Behind the scenes, this variable calls
247 ``request.user.get_and_delete_messages()`` for every request. That method
248 collects the user's messages and deletes them from the database.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
249
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
250 * ``perms``: An instance of ``django.core.context_processors.PermWrapper``,
251 which represents the permissions the current logged-in user has.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
252
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
253 See Chapter 14 for more information on users, permissions, and messages.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
254
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
255 django.core.context_processors.debug
256 ------------------------------------
257
258 This processor pushes debugging information down to the template layer. If
259 ``TEMPLATE_CONTEXT_PROCESSORS`` contains this processor, every
260 ``RequestContext`` will contain these variables:
261
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
262 * ``debug``: The value of your ``DEBUG`` setting (either ``True`` or
263 ``False``). You can use this variable in templates to test whether you're
264 in debug mode.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
265
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
266 * ``sql_queries``: A list of ``{'sql': ..., 'time': ...}`` dictionaries
267 representing every SQL query that has happened so far during the request
268 and how long it took. The list is in the order in which the queries were
269 issued.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
270
271 Because debugging information is sensitive, this context processor will only
272 add variables to the context if both of the following conditions are true:
273
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
274 * The ``DEBUG`` setting is ``True``.
275
276 * The request came from an IP address in the ``INTERNAL_IPS`` setting.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
277
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
278 Astute readers will notice that the ``debug`` template variable will never have
279 the value ``False`` because, if ``DEBUG`` is ``False``, then the ``debug``
280 template variable won't be populated in the first place.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
281
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
282 django.core.context_processors.i18n
283 -----------------------------------
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
284
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
285 If this processor is enabled, every ``RequestContext`` will contain these
286 variables:
287
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
288 * ``LANGUAGES``: The value of the ``LANGUAGES`` setting.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
289
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
290 * ``LANGUAGE_CODE``: ``request.LANGUAGE_CODE`` if it exists; otherwise, the
291 value of the ``LANGUAGE_CODE`` setting.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
292
293 Appendix D provides more information about these two settings.
294
295 django.core.context_processors.request
296 --------------------------------------
297
298 If this processor is enabled, every ``RequestContext`` will contain a variable
299 ``request``, which is the current ``HttpRequest`` object. Note that this
300 processor is not enabled by default; you have to activate it.
301
302 You might want to use this if you find your templates needing to access
303 attributes of the current ``HttpRequest`` such as the IP address::
304
305 {{ request.REMOTE_ADDR }}
306
307 Guidelines for Writing Your Own Context Processors
308 --------------------------------------------------
309
310 Here are a few tips for rolling your own:
311
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
312 * Make each context processor responsible for the smallest subset of
313 functionality possible. It's easy to use multiple processors, so you
314 might as well split functionality into logical pieces for future reuse.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
315
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
316 * Keep in mind that any context processor in ``TEMPLATE_CONTEXT_PROCESSORS``
317 will be available in *every* template powered by that settings file, so
318 try to pick variable names that are unlikely to conflict with variable
319 names your templates might be using independently. As variable names are
320 case-sensitive, it's not a bad idea to use all caps for variables that a
321 processor provides.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
322
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
323 * It doesn't matter where on the filesystem they live, as long as they're
324 on your Python path so you can point to them from the
325 ``TEMPLATE_CONTEXT_PROCESSORS`` setting. With that said, the convention
326 is to save them in a file called ``context_processors.py`` within your
327 app or project.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
328
329 Automatic HTML Escaping
330 =======================
331
332 When generating HTML from templates, there's always a risk that a variable will
333 include characters that affect the resulting HTML. For example, consider this
334 template fragment::
335
336 Hello, {{ name }}.
337
338 At first, this seems like a harmless way to display a user's name, but consider
339 what would happen if the user entered his name as this::
340
341 <script>alert('hello')</script>
342
343 With this name value, the template would be rendered as::
344
345 Hello, <script>alert('hello')</script>
346
347 ...which means the browser would pop-up a JavaScript alert box!
348
349 Similarly, what if the name contained a ``'<'`` symbol, like this?
350
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
351 ::
352
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
353 <b>username
354
355 That would result in a rendered template like this::
356
357 Hello, <b>username
358
359 ...which, in turn, would result in the remainder of the Web page being bolded!
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
360
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
361 Clearly, user-submitted data shouldn't be trusted blindly and inserted directly
362 into your Web pages, because a malicious user could use this kind of hole to
363 do potentially bad things. This type of security exploit is called a
364 Cross Site Scripting (XSS) attack. (For more on security, see Chapter 20.)
365
366 To avoid this problem, you have two options:
367
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
368 * One, you can make sure to run each untrusted variable through the
369 ``escape`` filter, which converts potentially harmful HTML characters to
370 unharmful ones. This was the default solution in Django for its first few
371 years, but the problem is that it puts the onus on *you*, the developer /
372 template author, to ensure you're escaping everything. It's easy to forget
373 to escape data.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
374
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
375 * Two, you can take advantage of Django's automatic HTML escaping. The
376 remainder of this section describes how auto-escaping works.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
377
378 By default in Django, every template automatically escapes the output
379 of every variable tag. Specifically, these five characters are
380 escaped:
381
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
382 * ``<`` is converted to ``&lt;``
383 * ``>`` is converted to ``&gt;``
384 * ``'`` (single quote) is converted to ``&#39;``
385 * ``"`` (double quote) is converted to ``&quot;``
386 * ``&`` is converted to ``&amp;``
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
387
388 Again, we stress that this behavior is on by default. If you're using Django's
389 template system, you're protected.
390
391 How to Turn it Off
392 ------------------
393
394 If you don't want data to be auto-escaped, on a per-site, per-template level or
395 per-variable level, you can turn it off in several ways.
396
397 Why would you want to turn it off? Because sometimes, template variables
398 contain data that you *intend* to be rendered as raw HTML, in which case you
399 don't want their contents to be escaped. For example, you might store a blob of
400 trusted HTML in your database and want to embed that directly into your
401 template. Or, you might be using Django's template system to produce text that
402 is *not* HTML -- like an e-mail message, for instance.
403
404 For Individual Variables
405 ~~~~~~~~~~~~~~~~~~~~~~~~
406
407 To disable auto-escaping for an individual variable, use the ``safe`` filter::
408
409 This will be escaped: {{ data }}
410 This will not be escaped: {{ data|safe }}
411
412 Think of *safe* as shorthand for *safe from further escaping* or *can be
413 safely interpreted as HTML*. In this example, if ``data`` contains ``'<b>'``,
414 the output will be::
415
416 This will be escaped: &lt;b&gt;
417 This will not be escaped: <b>
418
419 For Template Blocks
420 ~~~~~~~~~~~~~~~~~~~
421
422 To control auto-escaping for a template, wrap the template (or just a
423 particular section of the template) in the ``autoescape`` tag, like so::
424
425 {% autoescape off %}
426 Hello {{ name }}
427 {% endautoescape %}
428
429 The ``autoescape`` tag takes either ``on`` or ``off`` as its argument. At
430 times, you might want to force auto-escaping when it would otherwise be
431 disabled. Here is an example template::
432
433 Auto-escaping is on by default. Hello {{ name }}
434
435 {% autoescape off %}
436 This will not be auto-escaped: {{ data }}.
437
438 Nor this: {{ other_data }}
439 {% autoescape on %}
440 Auto-escaping applies again: {{ name }}
441 {% endautoescape %}
442 {% endautoescape %}
443
444 The auto-escaping tag passes its effect on to templates that extend the
445 current one as well as templates included via the ``include`` tag, just like
446 all block tags. For example::
447
448 # base.html
449
450 {% autoescape off %}
451 <h1>{% block title %}{% endblock %}</h1>
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
452 {% block content %}
453 {% endblock %}
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
454 {% endautoescape %}
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
455
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
456 # child.html
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
457
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
458 {% extends "base.html" %}
459 {% block title %}This & that{% endblock %}
460 {% block content %}{{ greeting }}{% endblock %}
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
461
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
462 Because auto-escaping is turned off in the base template, it will also be
463 turned off in the child template, resulting in the following rendered
464 HTML when the ``greeting`` variable contains the string ``<b>Hello!</b>``::
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
465
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
466 <h1>This & that</h1>
467 <b>Hello!</b>
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
468
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
469 Notes
470 -----
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
471
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
472 Generally, template authors don't need to worry about auto-escaping very much.
473 Developers on the Python side (people writing views and custom filters) need to
474 think about the cases in which data shouldn't be escaped, and mark data
475 appropriately, so things work in the template.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
476
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
477 If you're creating a template that might be used in situations where you're
478 not sure whether auto-escaping is enabled, then add an ``escape`` filter to any
479 variable that needs escaping. When auto-escaping is on, there's no danger of
480 the ``escape`` filter *double-escaping* data -- the ``escape`` filter does not
481 affect auto-escaped variables.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
482
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
483 Automatic Escaping of String Literals in Filter Arguments
484 ---------------------------------------------------------
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
485
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
486 As we mentioned earlier, filter arguments can be strings::
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
487
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
488 {{ data|default:"This is a string literal." }}
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
489
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
490 All string literals are inserted *without* any automatic escaping into the
491 template -- they act as if they were all passed through the ``safe`` filter.
492 The reasoning behind this is that the template author is in control of what
493 goes into the string literal, so they can make sure the text is correctly
494 escaped when the template is written.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
495
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
496 This means you would write ::
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
497
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
498 {{ data|default:"3 &lt; 2" }}
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
499
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
500 ...rather than ::
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
501
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
502 {{ data|default:"3 < 2" }} <-- Bad! Don't do this.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
503
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
504 This doesn't affect what happens to data coming from the variable itself.
505 The variable's contents are still automatically escaped, if necessary, because
506 they're beyond the control of the template author.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
507
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
508 Inside Template Loading
509 =======================
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
510
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
511 Generally, you'll store templates in files on your filesystem, but you can use
512 custom *template loaders* to load templates from other sources.
513
514 Django has two ways to load templates:
515
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
516 * ``django.template.loader.get_template(template_name)``: ``get_template``
517 returns the compiled template (a ``Template`` object) for the template
518 with the given name. If the template doesn't exist, a
519 ``TemplateDoesNotExist`` exception will be raised.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
520
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
521 * ``django.template.loader.select_template(template_name_list)``:
522 ``select_template`` is just like ``get_template``, except it takes a list
523 of template names. Of the list, it returns the first template that exists.
524 If none of the templates exist, a ``TemplateDoesNotExist`` exception will
525 be raised.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
526
527 As covered in Chapter 4, each of these functions by default uses your
528 ``TEMPLATE_DIRS`` setting to load templates. Internally, however, these
529 functions actually delegate to a template loader for the heavy lifting.
530
531 Some of loaders are disabled by default, but you can activate them by editing
532 the ``TEMPLATE_LOADERS`` setting. ``TEMPLATE_LOADERS`` should be a tuple of
533 strings, where each string represents a template loader. These template loaders
534 ship with Django:
535
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
536 * ``django.template.loaders.filesystem.load_template_source``: This loader
537 loads templates from the filesystem, according to ``TEMPLATE_DIRS``. It is
538 enabled by default.
539
540 * ``django.template.loaders.app_directories.load_template_source``: This
541 loader loads templates from Django applications on the filesystem. For
542 each application in ``INSTALLED_APPS``, the loader looks for a
543 ``templates`` subdirectory. If the directory exists, Django looks for
544 templates there.
545
546 This means you can store templates with your individual applications,
547 making it easy to distribute Django applications with default templates.
548 For example, if ``INSTALLED_APPS`` contains ``('myproject.polls',
549 'myproject.music')``, then ``get_template('foo.html')`` will look for
550 templates in this order:
551
552 * ``/path/to/myproject/polls/templates/foo.html``
553 * ``/path/to/myproject/music/templates/foo.html``
554
555 Note that the loader performs an optimization when it is first imported:
556 it caches a list of which ``INSTALLED_APPS`` packages have a ``templates``
557 subdirectory.
558
559 This loader is enabled by default.
560
561 * ``django.template.loaders.eggs.load_template_source``: This loader is just
562 like ``app_directories``, except it loads templates from Python eggs
563 rather than from the filesystem. This loader is disabled by default;
564 you'll need to enable it if you're using eggs to distribute your
565 application. (Python eggs are a way of compressing Python code into a
566 single file.)
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
567
568 Django uses the template loaders in order according to the ``TEMPLATE_LOADERS``
569 setting. It uses each loader until a loader finds a match.
570
571 Extending the Template System
572 =============================
573
574 Now that you understand a bit more about the internals of the template system,
575 let's look at how to extend the system with custom code.
576
577 Most template customization comes in the form of custom template tags and/or
578 filters. Although the Django template language comes with many built-in tags and
579 filters, you'll probably assemble your own libraries of tags and filters that
580 fit your own needs. Fortunately, it's quite easy to define your own
581 functionality.
582
583 Creating a Template Library
584 ---------------------------
585
586 Whether you're writing custom tags or filters, the first thing to do is to
587 create a **template library** -- a small bit of infrastructure Django can hook
588 into.
589
590 Creating a template library is a two-step process:
591
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
592 * First, decide which Django application should house the template library.
593 If you've created an app via ``manage.py startapp``, you can put it in
594 there, or you can create another app solely for the template library.
595 We'd recommend the latter, because your filters might be useful to you
596 in future projects.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
597
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
598 Whichever route you take, make sure to add the app to your
599 ``INSTALLED_APPS`` setting. We'll explain this shortly.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
600
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
601 * Second, create a ``templatetags`` directory in the appropriate Django
602 application's package. It should be on the same level as ``models.py``,
603 ``views.py``, and so forth. For example::
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
604
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
605 books/
606 __init__.py
607 models.py
608 templatetags/
609 views.py
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
610
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
611 Create two empty files in the ``templatetags`` directory: an ``__init__.py``
612 file (to indicate to Python that this is a package containing Python code)
613 and a file that will contain your custom tag/filter definitions. The name
614 of the latter file is what you'll use to load the tags later. For example,
615 if your custom tags/filters are in a file called ``poll_extras.py``, you'd
616 write the following in a template::
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
617
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
618 {% load poll_extras %}
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
619
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
620 The ``{% load %}`` tag looks at your ``INSTALLED_APPS`` setting and only
621 allows the loading of template libraries within installed Django
622 applications. This is a security feature; it allows you to host Python
623 code for many template libraries on a single computer without enabling
624 access to all of them for every Django installation.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
625
626 If you write a template library that isn't tied to any particular models/views,
627 it's valid and quite normal to have a Django application package that contains
628 only a ``templatetags`` package. There's no limit on how many modules you put in
629 the ``templatetags`` package. Just keep in mind that a ``{% load %}`` statement
630 will load tags/filters for the given Python module name, not the name of the
631 application.
632
633 Once you've created that Python module, you'll just have to write a bit of
634 Python code, depending on whether you're writing filters or tags.
635
636 To be a valid tag library, the module must contain a module-level variable named
637 ``register`` that is an instance of ``template.Library``. This is the data
638 structure in which all the tags and filters are registered. So, near the top of
639 your module, insert the following::
640
641 from django import template
642
643 register = template.Library()
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
644
645 .. note::
646
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
647 For a fine selection of examples, read the source code for Django's default
648 filters and tags. They're in ``django/template/defaultfilters.py`` and
649 ``django/template/defaulttags.py``, respectively. Some applications in
650 ``django.contrib`` also contain template libraries.
651
652 Once you've created this ``register`` variable, you'll use it to create template
653 filters and tags.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
654
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
655 Writing Custom Template Filters
656 -------------------------------
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
657
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
658 Custom filters are just Python functions that take one or two arguments:
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
659
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
660 * The value of the variable (input)
661
662 * The value of the argument, which can have a default value or be left out
663 altogether
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
664
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
665 For example, in the filter ``{{ var|foo:"bar" }}``, the filter ``foo`` would be
666 passed the contents of the variable ``var`` and the argument ``"bar"``.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
667
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
668 Filter functions should always return something. They shouldn't raise
669 exceptions, and they should fail silently. If there's an error, they should
670 return either the original input or an empty string, whichever makes more sense.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
671
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
672 Here's an example filter definition::
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
673
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
674 def cut(value, arg):
675 "Removes all values of arg from the given string"
676 return value.replace(arg, '')
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
677
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
678 And here's an example of how that filter would be used to cut spaces from a
679 variable's value::
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
680
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
681 {{ somevariable|cut:" " }}
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
682
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
683 Most filters don't take arguments. In this case, just leave the argument out
684 of your function::
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
685
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
686 def lower(value): # Only one argument.
687 "Converts a string into all lowercase"
688 return value.lower()
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
689
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
690 When you've written your filter definition, you need to register it with your
691 ``Library`` instance, to make it available to Django's template language::
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
692
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
693 register.filter('cut', cut)
694 register.filter('lower', lower)
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
695
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
696 .. SL Tested ok
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
697
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
698 The ``Library.filter()`` method takes two arguments:
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
699
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
700 * The name of the filter (a string)
701 * The filter function itself
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
702
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
703 If you're using Python 2.4 or above, you can use ``register.filter()`` as a
704 decorator instead::
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
705
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
706 @register.filter(name='cut')
707 def cut(value, arg):
708 return value.replace(arg, '')
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
709
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
710 @register.filter
711 def lower(value):
712 return value.lower()
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
713
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
714 .. SL Tested ok
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
715
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
716 If you leave off the ``name`` argument, as in the second example, Django
717 will use the function's name as the filter name.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
718
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
719 Here, then, is a complete template library example, supplying the ``cut`` filter::
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
720
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
721 from django import template
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
722
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
723 register = template.Library()
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
724
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
725 @register.filter(name='cut')
726 def cut(value, arg):
727 return value.replace(arg, '')
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
728
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
729 .. SL Tested ok
730
731 Writing Custom Template Tags
732 ----------------------------
733
734 Tags are more complex than filters, because tags can do nearly anything.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
735
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
736 Chapter 4 describes how the template system works in a two-step process:
737 compiling and rendering. To define a custom template tag, you need to tell
738 Django how to manage *both* of these steps when it gets to your tag.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
739
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
740 When Django compiles a template, it splits the raw template text into
741 *nodes*. Each node is an instance of ``django.template.Node`` and has
742 a ``render()`` method. Thus, a compiled template is simply a list of ``Node``
743 objects. For example, consider this template::
744
745 Hello, {{ person.name }}.
746
747 {% ifequal name.birthday today %}
748 Happy birthday!
749 {% else %}
750 Be sure to come back on your birthday
751 for a splendid surprise message.
752 {% endifequal %}
753
754 In compiled template form, this template is represented as this list of
755 nodes:
756
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
757 * Text node: ``"Hello, "``
758 * Variable node: ``person.name``
759 * Text node: ``".\n\n"``
760 * IfEqual node: ``name.birthday`` and ``today``
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
761
762 When you call ``render()`` on a compiled template, the template calls
763 ``render()`` on each ``Node`` in its node list, with the given context. The
764 results are all concatenated together to form the output of the template. Thus,
765 to define a custom template tag, you specify how the raw template tag is
766 converted into a ``Node`` (the compilation function) and what the node's
767 ``render()`` method does.
768
769 In the sections that follow, we cover all the steps in writing a custom tag.
770
771 Writing the Compilation Function
772 --------------------------------
773
774 For each template tag the parser encounters, it calls a Python function with
775 the tag contents and the parser object itself. This function is responsible for
776 returning a ``Node`` instance based on the contents of the tag.
777
778 For example, let's write a template tag, ``{% current_time %}``, that displays
779 the current date/time, formatted according to a parameter given in the tag, in
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
780 ``strftime`` syntax (see ``http://www.djangoproject.com/r/python/strftime/``).
781 It's a good idea to decide the tag syntax before anything else. In our case,
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
782 let's say the tag should be used like this::
783
784 <p>The time is {% current_time "%Y-%m-%d %I:%M %p" %}.</p>
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
785
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
786 .. note::
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
787
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
788 Yes, this template tag is redundant--Django's default ``{% now %}`` tag does
789 the same task with simpler syntax. This template tag is presented here just
790 for example purposes.
791
792 The parser for this function should grab the parameter and create a ``Node``
793 object::
794
795 from django import template
796
797 register = template.Library()
798
799 def do_current_time(parser, token):
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
800 try:
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
801 # split_contents() knows not to split quoted strings.
802 tag_name, format_string = token.split_contents()
803 except ValueError:
804 msg = '%r tag requires a single argument' % token.split_contents()[0]
805 raise template.TemplateSyntaxError(msg)
806 return CurrentTimeNode(format_string[1:-1])
807
808 There's a lot going here:
809
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
810 * Each template tag compilation function takes two arguments, ``parser``
811 and ``token``. ``parser`` is the template parser object. We don't use it
812 in this example. ``token`` is the token currently being parsed by the
813 parser.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
814
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
815 * ``token.contents`` is a string of the raw contents of the tag. In our
816 example, it's ``'current_time "%Y-%m-%d %I:%M %p"'``.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
817
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
818 * The ``token.split_contents()`` method separates the arguments on spaces
819 while keeping quoted strings together. Avoid using
820 ``token.contents.split()`` (which just uses Python's standard
821 string-splitting semantics). It's not as robust, as it naively splits on
822 *all* spaces, including those within quoted strings.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
823
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
824 * This function is responsible for raising
825 ``django.template.TemplateSyntaxError``, with helpful messages, for any
826 syntax error.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
827
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
828 * Don't hard-code the tag's name in your error messages, because that
829 couples the tag's name to your function. ``token.split_contents()[0]``
830 will *always* be the name of your tag -- even when the tag has no
831 arguments.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
832
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
833 * The function returns a ``CurrentTimeNode`` (which we'll create shortly)
834 containing everything the node needs to know about this tag. In this
835 case, it just passes the argument ``"%Y-%m-%d %I:%M %p"``. The
836 leading and trailing quotes from the template tag are removed with
837 ``format_string[1:-1]``.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
838
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
839 * Template tag compilation functions *must* return a ``Node`` subclass;
840 any other return value is an error.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
841
842 Writing the Template Node
843 -------------------------
844
845 The second step in writing custom tags is to define a ``Node`` subclass that
846 has a ``render()`` method. Continuing the preceding example, we need to define
847 ``CurrentTimeNode``::
848
849 import datetime
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
850
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
851 class CurrentTimeNode(template.Node):
852 def __init__(self, format_string):
853 self.format_string = str(format_string)
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
854
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
855 def render(self, context):
856 now = datetime.datetime.now()
857 return now.strftime(self.format_string)
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
858
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
859 These two functions (``__init__()`` and ``render()``) map directly to the two
860 steps in template processing (compilation and rendering). Thus, the
861 initialization function only needs to store the format string for later use,
862 and the ``render()`` function does the real work.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
863
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
864 Like template filters, these rendering functions should fail silently instead
865 of raising errors. The only time that template tags are allowed to raise
866 errors is at compilation time.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
867
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
868 Registering the Tag
869 -------------------
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
870
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
871 Finally, you need to register the tag with your module's ``Library`` instance.
872 Registering custom tags is very similar to registering custom filters (as
873 explained above). Just instantiate a ``template.Library`` instance and call
874 its ``tag()`` method. For example::
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
875
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
876 register.tag('current_time', do_current_time)
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
877
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
878 The ``tag()`` method takes two arguments:
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
879
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
880 * The name of the template tag (string).
881 * The compilation function.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
882
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
883 As with filter registration, it is also possible to use ``register.tag`` as a
884 decorator in Python 2.4 and above::
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
885
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
886 @register.tag(name="current_time")
887 def do_current_time(parser, token):
888 # ...
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
889
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
890 @register.tag
891 def shout(parser, token):
892 # ...
893
894 If you leave off the ``name`` argument, as in the second example, Django
895 will use the function's name as the tag name.
896
897 Setting a Variable in the Context
898 ---------------------------------
899
900 The previous section's example simply returned a value. Often it's useful to set
901 template variables instead of returning values. That way, template authors can
902 just use the variables that your template tags set.
903
904 To set a variable in the context, use dictionary assignment on the context
905 object in the ``render()`` method. Here's an updated version of
906 ``CurrentTimeNode`` that sets a template variable, ``current_time``, instead of
907 returning it::
908
909 class CurrentTimeNode2(template.Node):
910 def __init__(self, format_string):
911 self.format_string = str(format_string)
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
912
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
913 def render(self, context):
914 now = datetime.datetime.now()
915 context['current_time'] = now.strftime(self.format_string)
916 return ''
917
918 (We'll leave the creation of a ``do_current_time2`` function, plus the
919 registration of that function to a ``current_time2`` template tag, as exercises
920 for the reader.)
921
922 Note that ``render()`` returns an empty string. ``render()`` should always
923 return a string, so if all the template tag does is set a variable,
924 ``render()`` should return an empty string.
925
926 Here's how you'd use this new version of the tag::
927
928 {% current_time2 "%Y-%M-%d %I:%M %p" %}
929 <p>The time is {{ current_time }}.</p>
930
931 But there's a problem with ``CurrentTimeNode2``: the variable name
932 ``current_time`` is hard-coded. This means you'll need to make sure your
933 template doesn't use ``{{ current_time }}`` anywhere else, because
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
934 ``{% current_time2 %}`` will blindly overwrite that variable's value.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
935
936 A cleaner solution is to make the template tag specify the name of the variable
937 to be set, like so::
938
939 {% get_current_time "%Y-%M-%d %I:%M %p" as my_current_time %}
940 <p>The current time is {{ my_current_time }}.</p>
941
942 To do so, you'll need to refactor both the compilation function and the
943 ``Node`` class, as follows::
944
945 import re
946
947 class CurrentTimeNode3(template.Node):
948 def __init__(self, format_string, var_name):
949 self.format_string = str(format_string)
950 self.var_name = var_name
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
951
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
952 def render(self, context):
953 now = datetime.datetime.now()
954 context[self.var_name] = now.strftime(self.format_string)
955 return ''
956
957 def do_current_time(parser, token):
958 # This version uses a regular expression to parse tag contents.
959 try:
960 # Splitting by None == splitting by spaces.
961 tag_name, arg = token.contents.split(None, 1)
962 except ValueError:
963 msg = '%r tag requires arguments' % token.contents[0]
964 raise template.TemplateSyntaxError(msg)
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
965
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
966 m = re.search(r'(.*?) as (\w+)', arg)
967 if m:
968 fmt, var_name = m.groups()
969 else:
970 msg = '%r tag had invalid arguments' % tag_name
971 raise template.TemplateSyntaxError(msg)
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
972
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
973 if not (fmt[0] == fmt[-1] and fmt[0] in ('"', "'")):
974 msg = "%r tag's argument should be in quotes" % tag_name
975 raise template.TemplateSyntaxError(msg)
976
977 return CurrentTimeNode3(fmt[1:-1], var_name)
978
979 Now ``do_current_time()`` passes the format string and the variable name to
980 ``CurrentTimeNode3``.
981
982 Parsing Until Another Template Tag
983 ----------------------------------
984
985 Template tags can work as blocks containing other tags (like ``{% if %}``,
986 ``{% for %}``, etc.). To create a template tag like this, use
987 ``parser.parse()`` in your compilation function.
988
989 Here's how the standard ``{% comment %}`` tag is implemented::
990
991 def do_comment(parser, token):
992 nodelist = parser.parse(('endcomment',))
993 parser.delete_first_token()
994 return CommentNode()
995
996 class CommentNode(template.Node):
997 def render(self, context):
998 return ''
999
1000 .. SL Tested ok
1001
1002 ``parser.parse()`` takes a tuple of names of template tags to parse until. It
1003 returns an instance of ``django.template.NodeList``, which is a list of all
1004 ``Node`` objects that the parser encountered *before* it encountered any of
1005 the tags named in the tuple.
1006
1007 So in the preceding example, ``nodelist`` is a list of all nodes between
1008 ``{% comment %}`` and ``{% endcomment %}``, not counting ``{% comment %}`` and
1009 ``{% endcomment %}`` themselves.
1010
1011 After ``parser.parse()`` is called, the parser hasn't yet "consumed" the ``{%
1012 endcomment %}`` tag, so the code needs to explicitly call
1013 ``parser.delete_first_token()`` to prevent that tag from being processed
1014 twice.
1015
1016 Then ``CommentNode.render()`` simply returns an empty string. Anything
1017 between ``{% comment %}`` and ``{% endcomment %}`` is ignored.
1018
1019 Parsing Until Another Template Tag and Saving Contents
1020 ------------------------------------------------------
1021
1022 In the previous example, ``do_comment()`` discarded everything between
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
1023 ``{% comment %}`` and ``{% endcomment %}``. It's also
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
1024 possible to do something with the code between template tags instead.
1025
1026 For example, here's a custom template tag, ``{% upper %}``, that capitalizes
1027 everything between itself and ``{% endupper %}``::
1028
1029 {% upper %}
1030 This will appear in uppercase, {{ user_name }}.
1031 {% endupper %}
1032
1033 As in the previous example, we'll use ``parser.parse()``. This time, we
1034 pass the resulting ``nodelist`` to ``Node``::
1035
1036 def do_upper(parser, token):
1037 nodelist = parser.parse(('endupper',))
1038 parser.delete_first_token()
1039 return UpperNode(nodelist)
1040
1041 class UpperNode(template.Node):
1042 def __init__(self, nodelist):
1043 self.nodelist = nodelist
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
1044
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
1045 def render(self, context):
1046 output = self.nodelist.render(context)
1047 return output.upper()
1048
1049 .. SL Tested ok
1050
1051 The only new concept here is ``self.nodelist.render(context)`` in
1052 ``UpperNode.render()``. This simply calls ``render()`` on each ``Node`` in the
1053 node list.
1054
1055 For more examples of complex rendering, see the source code for ``{% if %}``,
1056 ``{% for %}``, ``{% ifequal %}``, and ``{% ifchanged %}``. They live in
1057 ``django/template/defaulttags.py``.
1058
1059 Shortcut for Simple Tags
1060 ------------------------
1061
1062 Many template tags take a single argument -- a string or a template variable
1063 reference -- and return a string after doing some processing based solely on
1064 the input argument and some external information. For example, the
1065 ``current_time`` tag we wrote earlier is of this variety. We give it a format
1066 string, and it returns the time as a string.
1067
1068 To ease the creation of these types of tags, Django provides a helper function,
1069 ``simple_tag``. This function, which is a method of ``django.template.Library``,
1070 takes a function that accepts one argument, wraps it in a ``render`` function
1071 and the other necessary bits mentioned previously, and registers it with the
1072 template system.
1073
1074 Our earlier ``current_time`` function could thus be written like this::
1075
1076 def current_time(format_string):
1077 try:
1078 return datetime.datetime.now().strftime(str(format_string))
1079 except UnicodeEncodeError:
1080 return ''
1081
1082 register.simple_tag(current_time)
1083
1084 In Python 2.4, the decorator syntax also works::
1085
1086 @register.simple_tag
1087 def current_time(token):
1088 # ...
1089
1090 Notice a couple of things to notice about the ``simple_tag`` helper function:
1091
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
1092 * Only the (single) argument is passed into our function.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
1093
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
1094 * Checking for the required number of arguments has already been
1095 done by the time our function is called, so we don't need to do that.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
1096
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
1097 * The quotes around the argument (if any) have already been stripped away,
1098 so we receive a plain Unicode string.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
1099
1100 Inclusion Tags
1101 --------------
1102
1103 Another common template tag is the type that displays some data by
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
1104 rendering *another* template. For example, Django's admin interface uses
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
1105 custom template tags to display the buttons along the bottom of the
1106 "add/change" form pages. Those buttons always look the same, but the link
1107 targets change depending on the object being edited. They're a perfect case
1108 for using a small template that is filled with details from the current object.
1109
1110 These sorts of tags are called *inclusion tags*. Writing inclusion tags is
1111 probably best demonstrated by example. Let's write a tag that produces a list
1112 of books for a given ``Author`` object. We'll use the tag like this::
1113
1114 {% books_for_author author %}
1115
1116 The result will be something like this::
1117
1118 <ul>
1119 <li>The Cat In The Hat</li>
1120 <li>Hop On Pop</li>
1121 <li>Green Eggs And Ham</li>
1122 </ul>
1123
1124 First, we define the function that takes the argument and produces a
1125 dictionary of data for the result. Notice that we need to return only a
1126 dictionary, not anything more complex. This will be used as the context for
1127 the template fragment::
1128
1129 def books_for_author(author):
1130 books = Book.objects.filter(authors__id=author.id)
1131 return {'books': books}
1132
1133 Next, we create the template used to render the tag's output. Following our
1134 example, the template is very simple::
1135
1136 <ul>
1137 {% for book in books %}
1138 <li>{{ book.title }}</li>
1139 {% endfor %}
1140 </ul>
1141
1142 Finally, we create and register the inclusion tag by calling the
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
1143 ``inclusion_tag()`` method on a ``Library`` object.
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
1144
1145 Following our example, if the preceding template is in a file called
1146 ``book_snippet.html``, we register the tag like this::
1147
1148 register.inclusion_tag('book_snippet.html')(books_for_author)
1149
1150 Python 2.4 decorator syntax works as well, so we could have written this,
1151 instead::
1152
1153 @register.inclusion_tag('book_snippet.html')
1154 def books_for_author(author):
1155 # ...
1156
1157 Sometimes, your inclusion tags need access to values from the parent template's
1158 context. To solve this, Django provides a ``takes_context`` option for
1159 inclusion tags. If you specify ``takes_context`` in creating an inclusion tag,
1160 the tag will have no required arguments, and the underlying Python function
1161 will have one argument: the template context as of when the tag was called.
1162
1163 For example, say you're writing an inclusion tag that will always be used in a
1164 context that contains ``home_link`` and ``home_title`` variables that point
1165 back to the main page. Here's what the Python function would look like::
1166
1167 @register.inclusion_tag('link.html', takes_context=True)
1168 def jump_link(context):
1169 return {
1170 'link': context['home_link'],
1171 'title': context['home_title'],
1172 }
1173
1174 (Note that the first parameter to the function *must* be called ``context``.)
1175
1176 The template ``link.html`` might contain the following::
1177
1178 Jump directly to <a href="{{ link }}">{{ title }}</a>.
1179
1180 Then, anytime you want to use that custom tag, load its library and call it
1181 without any arguments, like so::
1182
1183 {% jump_link %}
1184
1185 Writing Custom Template Loaders
1186 ===============================
1187
1188 Django's built-in template loaders (described in the "Inside Template Loading"
1189 section above) will usually cover all your template-loading needs, but it's
1190 pretty easy to write your own if you need special loading logic. For example,
1191 you could load templates from a database, or directly from a Subversion
1192 repository using Subversion's Python bindings, or (as shown shortly) from a ZIP
1193 archive.
1194
1195 A template loader -- that is, each entry in the ``TEMPLATE_LOADERS`` setting
1196 -- is expected to be a callable object with this interface::
1197
1198 load_template_source(template_name, template_dirs=None)
1199
1200 The ``template_name`` argument is the name of the template to load (as passed
1201 to ``loader.get_template()`` or ``loader.select_template()``), and
1202 ``template_dirs`` is an optional list of directories to search instead of
1203 ``TEMPLATE_DIRS``.
1204
1205 If a loader is able to successfully load a template, it should return a tuple:
1206 ``(template_source, template_path)``. Here, ``template_source`` is the
1207 template string that will be compiled by the template engine, and
1208 ``template_path`` is the path the template was loaded from. That path might be
1209 shown to the user for debugging purposes, so it should quickly identify where
1210 the template was loaded from.
1211
1212 If the loader is unable to load a template, it should raise
1213 ``django.template.TemplateDoesNotExist``.
1214
1215 Each loader function should also have an ``is_usable`` function attribute.
1216 This is a Boolean that informs the template engine whether this loader
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
1217 is available in the current Python installation. For example, the eggs loader
1218 (which is capable of loading templates from Python eggs) sets ``is_usable``
1219 to ``False`` if the ``pkg_resources`` module isn't installed, because
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
1220 ``pkg_resources`` is necessary to read data from eggs.
1221
1222 An example should help clarify all of this. Here's a template loader function
1223 that can load templates from a ZIP file. It uses a custom setting,
1224 ``TEMPLATE_ZIP_FILES``, as a search path instead of ``TEMPLATE_DIRS``, and it
1225 expects each item on that path to be a ZIP file containing templates::
1226
1227 from django.conf import settings
1228 from django.template import TemplateDoesNotExist
1229 import zipfile
1230
1231 def load_template_source(template_name, template_dirs=None):
1232 "Template loader that loads templates from a ZIP file."
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
1233
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
1234 template_zipfiles = getattr(settings, "TEMPLATE_ZIP_FILES", [])
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
1235
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
1236 # Try each ZIP file in TEMPLATE_ZIP_FILES.
1237 for fname in template_zipfiles:
1238 try:
1239 z = zipfile.ZipFile(fname)
1240 source = z.read(template_name)
1241 except (IOError, KeyError):
1242 continue
1243 z.close()
1244 # We found a template, so return the source.
1245 template_path = "%s:%s" % (fname, template_name)
1246 return (source, template_path)
1247
1248 # If we reach here, the template couldn't be loaded
1249 raise TemplateDoesNotExist(template_name)
1250
1251 # This loader is always usable (since zipfile is included with Python)
1252 load_template_source.is_usable = True
1253
1254 .. SL Tested ok
1255
1256 The only step left if we want to use this loader is to add it to the
1257 ``TEMPLATE_LOADERS`` setting. If we put this code in a package called
fdc4800 Jacob Kaplan-Moss Fixed a bunch of reST markup errors.
jacobian authored
1258 ``mysite.zip_loader``, then we add
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
1259 ``mysite.zip_loader.load_template_source`` to ``TEMPLATE_LOADERS``.
1260
1261 Configuring the Template System in Standalone Mode
1262 ==================================================
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
1263
1264 .. note::
1265
d40cfe7 Jacob Kaplan-Moss Restored *2.0* version of the book, not 1.0!
jacobian authored
1266 This section is only of interest to people trying to use the template
1267 system as an output component in another application. If you are using the
1268 template system as part of a Django application, the information presented
1269 here doesn't apply to you.
1270
1271 Normally, Django loads all the configuration information it needs from its own
1272 default configuration file, combined with the settings in the module given
1273 in the ``DJANGO_SETTINGS_MODULE`` environment variable. (This was explained in
1274 "A special Python prompt" in Chapter 4.) But if you're using the template
1275 system independently of the rest of Django, the environment variable approach
1276 isn't very convenient, because you probably want to configure the template
1277 system in line with the rest of your application rather than dealing with
1278 settings files and pointing to them via environment variables.
1279
1280 To solve this problem, you need to use the manual configuration option described
1281 fully in Appendix D. In a nutshell, you need to import the appropriate pieces of
1282 the template system and then, *before* you call any of the template functions,
1283 call ``django.conf.settings.configure()`` with any settings you wish to specify.
1284
1285 You might want to consider setting at least ``TEMPLATE_DIRS`` (if you are
1286 going to use template loaders), ``DEFAULT_CHARSET`` (although the default of
1287 ``utf-8`` is probably fine) and ``TEMPLATE_DEBUG``. All available settings are
1288 described in Appendix D, and any setting starting with ``TEMPLATE_`` is of
1289 obvious interest.
1290
1291 What's Next
1292 ===========
1293
1294 Continuing this section's theme of advanced topics, the `next chapter`_ covers
1295 advanced usage of Django models.
acc918f Jacob Kaplan-Moss Initial import of djangobook from private SVN repo.
jacobian authored
1296
585d4c4 belgianguy Removed trailing slash, rst to html
belgianguy authored
1297 .. _next chapter: chapter10.html
Something went wrong with that request. Please try again.