PageRenderTime 72ms CodeModel.GetById 51ms app.highlight 5ms RepoModel.GetById 4ms app.codeStats 0ms

/docs/topics/templates.txt

https://code.google.com/p/mango-py/
Plain Text | 658 lines | 475 code | 183 blank | 0 comment | 0 complexity | fe9f94710830a31644c987ece2c9f85c MD5 | raw file
  1============================
  2The Django template language
  3============================
  4
  5.. admonition:: About this document
  6
  7    This document explains the language syntax of the Django template system. If
  8    you're looking for a more technical perspective on how it works and how to
  9    extend it, see :doc:`/ref/templates/api`.
 10
 11Django's template language is designed to strike a balance between power and
 12ease. It's designed to feel comfortable to those used to working with HTML. If
 13you have any exposure to other text-based template languages, such as Smarty_
 14or CheetahTemplate_, you should feel right at home with Django's templates.
 15
 16.. admonition:: Philosophy
 17
 18    If you have a background in programming, or if you're used to languages
 19    like PHP which mix programming code directly into HTML, you'll want to
 20    bear in mind that the Django template system is not simply Python embedded
 21    into HTML. This is by design: the template system is meant to express
 22    presentation, not program logic.
 23
 24    The Django template system provides tags which function similarly to some
 25    programming constructs -- an :ttag:`if` tag for boolean tests, a :ttag:`for`
 26    tag for looping, etc. -- but these are not simply executed as the
 27    corresponding Python code, and the template system will not execute
 28    arbitrary Python expressions. Only the tags, filters and syntax listed below
 29    are supported by default (although you can add :doc:`your own extensions
 30    </howto/custom-template-tags>` to the template language as needed).
 31
 32.. _`The Django template language: For Python programmers`: ../templates_python/
 33.. _Smarty: http://smarty.php.net/
 34.. _CheetahTemplate: http://www.cheetahtemplate.org/
 35
 36Templates
 37=========
 38
 39.. highlightlang:: html+django
 40
 41A template is simply a text file. It can generate any text-based format (HTML,
 42XML, CSV, etc.).
 43
 44A template contains **variables**, which get replaced with values when the
 45template is evaluated, and **tags**, which control the logic of the template.
 46
 47Below is a minimal template that illustrates a few basics. Each element will be
 48explained later in this document.::
 49
 50    {% extends "base_generic.html" %}
 51
 52    {% block title %}{{ section.title }}{% endblock %}
 53
 54    {% block content %}
 55    <h1>{{ section.title }}</h1>
 56
 57    {% for story in story_list %}
 58    <h2>
 59      <a href="{{ story.get_absolute_url }}">
 60        {{ story.headline|upper }}
 61      </a>
 62    </h2>
 63    <p>{{ story.tease|truncatewords:"100" }}</p>
 64    {% endfor %}
 65    {% endblock %}
 66
 67.. admonition:: Philosophy
 68
 69    Why use a text-based template instead of an XML-based one (like Zope's
 70    TAL)? We wanted Django's template language to be usable for more than
 71    just XML/HTML templates. At World Online, we use it for e-mails,
 72    JavaScript and CSV. You can use the template language for any text-based
 73    format.
 74
 75    Oh, and one more thing: Making humans edit XML is sadistic!
 76
 77Variables
 78=========
 79
 80Variables look like this: ``{{ variable }}``. When the template engine
 81encounters a variable, it evaluates that variable and replaces it with the
 82result. Variable names consist of any combination of alphanumeric characters
 83and the underscore (``"_"``). The dot (``"."``) also appears in variable
 84sections, although that has a special meaning, as indicated below.
 85Importantly, *you cannot have spaces or punctuation characters in variable
 86names.*
 87
 88Use a dot (``.``) to access attributes of a variable.
 89
 90.. admonition:: Behind the scenes
 91
 92    Technically, when the template system encounters a dot, it tries the
 93    following lookups, in this order:
 94
 95        * Dictionary lookup
 96        * Attribute lookup
 97        * Method call
 98        * List-index lookup
 99
100In the above example, ``{{ section.title }}`` will be replaced with the
101``title`` attribute of the ``section`` object.
102
103If you use a variable that doesn't exist, the template system will insert
104the value of the :setting:`TEMPLATE_STRING_IF_INVALID` setting, which is set
105to ``''`` (the empty string) by default.
106
107Filters
108=======
109
110You can modify variables for display by using **filters**.
111
112Filters look like this: ``{{ name|lower }}``. This displays the value of the
113``{{ name }}`` variable after being filtered through the ``lower`` filter,
114which converts text to lowercase. Use a pipe (``|``) to apply a filter.
115
116Filters can be "chained." The output of one filter is applied to the next.
117``{{ text|escape|linebreaks }}`` is a common idiom for escaping text contents,
118then converting line breaks to ``<p>`` tags.
119
120Some filters take arguments. A filter argument looks like this: ``{{
121bio|truncatewords:30 }}``. This will display the first 30 words of the ``bio``
122variable.
123
124Filter arguments that contain spaces must be quoted; for example, to join a list
125with commas and spaced you'd use ``{{ list|join:", " }}``.
126
127Django provides about thirty built-in template filters. You can read all about
128them in the :ref:`built-in filter reference <ref-templates-builtins-filters>`.
129To give you a taste of what's available, here are some of the more commonly used
130template filters:
131
132    :tfilter:`default`
133        If a variable is false or empty, use given default. Otherwise, use the
134        value of the variable
135
136        For example::
137
138            {{ value|default:"nothing" }}
139
140        If ``value`` isn't provided or is empty, the above will display
141        "``nothing``".
142
143    :tfilter:`length`
144        Returns the length of the value. This works for both strings and lists;
145        for example::
146
147            {{ value|length }}
148
149        If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``4``.
150
151    :tfilter:`striptags`
152        Strips all [X]HTML tags. For example::
153
154            {{ value|striptags }}
155
156        If ``value`` is ``"<b>Joel</b> <button>is</button> a
157        <span>slug</span>"``, the output will be ``"Joel is a slug"``.
158
159Again, these are just a few examples; see the :ref:`built-in filter reference
160<ref-templates-builtins-filters>` for the complete list.
161
162You can also create your own custom template filters; see
163:doc:`/howto/custom-template-tags`.
164
165.. seealso::
166
167    Django's admin interface can include a complete reference of all template
168    tags and filters available for a given site. See
169    :doc:`/ref/contrib/admin/admindocs`.
170
171Tags
172====
173
174Tags look like this: ``{% tag %}``. Tags are more complex than variables: Some
175create text in the output, some control flow by performing loops or logic, and
176some load external information into the template to be used by later variables.
177
178Some tags require beginning and ending tags (i.e. ``{% tag %} ... tag contents
179... {% endtag %}``).
180
181Django ships with about two dozen built-in template tags. You can read all about
182them in the :ref:`built-in tag reference <ref-templates-builtins-tags>`. To give
183you a taste of what's available, here are some of the more commonly used
184tags:
185
186    :ttag:`for`
187        Loop over each item in an array.  For example, to display a list of athletes
188        provided in ``athlete_list``::
189
190            <ul>
191            {% for athlete in athlete_list %}
192                <li>{{ athlete.name }}</li>
193            {% endfor %}
194            </ul>
195
196    :ttag:`if` and ``else``
197        Evaluates a variable, and if that variable is "true" the contents of the
198        block are displayed::
199
200            {% if athlete_list %}
201                Number of athletes: {{ athlete_list|length }}
202            {% else %}
203                No athletes.
204            {% endif %}
205
206        In the above, if ``athlete_list`` is not empty, the number of athletes
207        will be displayed by the ``{{ athlete_list|length }}`` variable.
208
209        You can also use filters and various operators in the ``if`` tag::
210
211            {% if athlete_list|length > 1 %}
212               Team: {% for athlete in athlete_list %} ... {% endfor %}
213            {% else %}
214               Athlete: {{ athlete_list.0.name }}
215            {% endif %}
216
217    :ttag:`block` and :ttag:`extends`
218        Set up `template inheritance`_ (see below), a powerful way
219        of cutting down on "boilerplate" in templates.
220
221Again, the above is only a selection of the whole list; see the :ref:`built-in
222tag reference <ref-templates-builtins-tags>` for the complete list.
223
224You can also create your own custom template tags; see
225:doc:`/howto/custom-template-tags`.
226
227.. seealso::
228
229    Django's admin interface can include a complete reference of all template
230    tags and filters available for a given site. See
231    :doc:`/ref/contrib/admin/admindocs`.
232
233Comments
234========
235
236To comment-out part of a line in a template, use the comment syntax: ``{# #}``.
237
238For example, this template would render as ``'hello'``::
239
240    {# greeting #}hello
241
242A comment can contain any template code, invalid or not. For example::
243
244    {# {% if foo %}bar{% else %} #}
245
246This syntax can only be used for single-line comments (no newlines are permitted
247between the ``{#`` and ``#}`` delimiters). If you need to comment out a
248multiline portion of the template, see the :ttag:`comment` tag.
249
250.. _template-inheritance:
251
252Template inheritance
253====================
254
255The most powerful -- and thus the most complex -- part of Django's template
256engine is template inheritance. Template inheritance allows you to build a base
257"skeleton" template that contains all the common elements of your site and
258defines **blocks** that child templates can override.
259
260It's easiest to understand template inheritance by starting with an example::
261
262    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
263        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
264    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
265    <head>
266        <link rel="stylesheet" href="style.css" />
267        <title>{% block title %}My amazing site{% endblock %}</title>
268    </head>
269
270    <body>
271        <div id="sidebar">
272            {% block sidebar %}
273            <ul>
274                <li><a href="/">Home</a></li>
275                <li><a href="/blog/">Blog</a></li>
276            </ul>
277            {% endblock %}
278        </div>
279
280        <div id="content">
281            {% block content %}{% endblock %}
282        </div>
283    </body>
284    </html>
285
286This template, which we'll call ``base.html``, defines a simple HTML skeleton
287document that you might use for a simple two-column page. It's the job of
288"child" templates to fill the empty blocks with content.
289
290In this example, the ``{% block %}`` tag defines three blocks that child
291templates can fill in. All the ``block`` tag does is to tell the template
292engine that a child template may override those portions of the template.
293
294A child template might look like this::
295
296    {% extends "base.html" %}
297
298    {% block title %}My amazing blog{% endblock %}
299
300    {% block content %}
301    {% for entry in blog_entries %}
302        <h2>{{ entry.title }}</h2>
303        <p>{{ entry.body }}</p>
304    {% endfor %}
305    {% endblock %}
306
307The ``{% extends %}`` tag is the key here. It tells the template engine that
308this template "extends" another template. When the template system evaluates
309this template, first it locates the parent -- in this case, "base.html".
310
311At that point, the template engine will notice the three ``{% block %}`` tags
312in ``base.html`` and replace those blocks with the contents of the child
313template. Depending on the value of ``blog_entries``, the output might look
314like::
315
316    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
317        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
318    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
319    <head>
320        <link rel="stylesheet" href="style.css" />
321        <title>My amazing blog</title>
322    </head>
323
324    <body>
325        <div id="sidebar">
326            <ul>
327                <li><a href="/">Home</a></li>
328                <li><a href="/blog/">Blog</a></li>
329            </ul>
330        </div>
331
332        <div id="content">
333            <h2>Entry one</h2>
334            <p>This is my first entry.</p>
335
336            <h2>Entry two</h2>
337            <p>This is my second entry.</p>
338        </div>
339    </body>
340    </html>
341
342Note that since the child template didn't define the ``sidebar`` block, the
343value from the parent template is used instead. Content within a ``{% block %}``
344tag in a parent template is always used as a fallback.
345
346You can use as many levels of inheritance as needed. One common way of using
347inheritance is the following three-level approach:
348
349    * Create a ``base.html`` template that holds the main look-and-feel of your
350      site.
351    * Create a ``base_SECTIONNAME.html`` template for each "section" of your
352      site. For example, ``base_news.html``, ``base_sports.html``. These
353      templates all extend ``base.html`` and include section-specific
354      styles/design.
355    * Create individual templates for each type of page, such as a news
356      article or blog entry. These templates extend the appropriate section
357      template.
358
359This approach maximizes code reuse and makes it easy to add items to shared
360content areas, such as section-wide navigation.
361
362Here are some tips for working with inheritance:
363
364    * If you use ``{% extends %}`` in a template, it must be the first template
365      tag in that template. Template inheritance won't work, otherwise.
366
367    * More ``{% block %}`` tags in your base templates are better. Remember,
368      child templates don't have to define all parent blocks, so you can fill
369      in reasonable defaults in a number of blocks, then only define the ones
370      you need later. It's better to have more hooks than fewer hooks.
371
372    * If you find yourself duplicating content in a number of templates, it
373      probably means you should move that content to a ``{% block %}`` in a
374      parent template.
375
376    * If you need to get the content of the block from the parent template,
377      the ``{{ block.super }}`` variable will do the trick. This is useful
378      if you want to add to the contents of a parent block instead of
379      completely overriding it. Data inserted using ``{{ block.super }}`` will
380      not be automatically escaped (see the `next section`_), since it was
381      already escaped, if necessary, in the parent template.
382
383    * For extra readability, you can optionally give a *name* to your
384      ``{% endblock %}`` tag. For example::
385
386          {% block content %}
387          ...
388          {% endblock content %}
389
390      In larger templates, this technique helps you see which ``{% block %}``
391      tags are being closed.
392
393Finally, note that you can't define multiple ``{% block %}`` tags with the same
394name in the same template. This limitation exists because a block tag works in
395"both" directions. That is, a block tag doesn't just provide a hole to fill --
396it also defines the content that fills the hole in the *parent*. If there were
397two similarly-named ``{% block %}`` tags in a template, that template's parent
398wouldn't know which one of the blocks' content to use.
399
400.. _next section: #automatic-html-escaping
401.. _automatic-html-escaping:
402
403Automatic HTML escaping
404=======================
405
406When generating HTML from templates, there's always a risk that a variable will
407include characters that affect the resulting HTML. For example, consider this
408template fragment::
409
410    Hello, {{ name }}.
411
412At first, this seems like a harmless way to display a user's name, but consider
413what would happen if the user entered his name as this::
414
415    <script>alert('hello')</script>
416
417With this name value, the template would be rendered as::
418
419    Hello, <script>alert('hello')</script>
420
421...which means the browser would pop-up a JavaScript alert box!
422
423Similarly, what if the name contained a ``'<'`` symbol, like this?
424
425    <b>username
426
427That would result in a rendered template like this::
428
429    Hello, <b>username
430
431...which, in turn, would result in the remainder of the Web page being bolded!
432
433Clearly, user-submitted data shouldn't be trusted blindly and inserted directly
434into your Web pages, because a malicious user could use this kind of hole to
435do potentially bad things. This type of security exploit is called a
436`Cross Site Scripting`_ (XSS) attack.
437
438To avoid this problem, you have two options:
439
440    * One, you can make sure to run each untrusted variable through the
441      ``escape`` filter (documented below), which converts potentially harmful
442      HTML characters to unharmful ones. This was the default solution
443      in Django for its first few years, but the problem is that it puts the
444      onus on *you*, the developer / template author, to ensure you're escaping
445      everything. It's easy to forget to escape data.
446
447    * Two, you can take advantage of Django's automatic HTML escaping. The
448      remainder of this section describes how auto-escaping works.
449
450By default in Django, every template automatically escapes the output
451of every variable tag. Specifically, these five characters are
452escaped:
453
454    * ``<`` is converted to ``&lt;``
455    * ``>`` is converted to ``&gt;``
456    * ``'`` (single quote) is converted to ``&#39;``
457    * ``"`` (double quote) is converted to ``&quot;``
458    * ``&`` is converted to ``&amp;``
459
460Again, we stress that this behavior is on by default. If you're using Django's
461template system, you're protected.
462
463.. _Cross Site Scripting: http://en.wikipedia.org/wiki/Cross-site_scripting
464
465How to turn it off
466------------------
467
468If you don't want data to be auto-escaped, on a per-site, per-template level or
469per-variable level, you can turn it off in several ways.
470
471Why would you want to turn it off? Because sometimes, template variables
472contain data that you *intend* to be rendered as raw HTML, in which case you
473don't want their contents to be escaped. For example, you might store a blob of
474HTML in your database and want to embed that directly into your template. Or,
475you might be using Django's template system to produce text that is *not* HTML
476-- like an e-mail message, for instance.
477
478For individual variables
479~~~~~~~~~~~~~~~~~~~~~~~~
480
481To disable auto-escaping for an individual variable, use the ``safe`` filter::
482
483    This will be escaped: {{ data }}
484    This will not be escaped: {{ data|safe }}
485
486Think of *safe* as shorthand for *safe from further escaping* or *can be
487safely interpreted as HTML*. In this example, if ``data`` contains ``'<b>'``,
488the output will be::
489
490    This will be escaped: &lt;b&gt;
491    This will not be escaped: <b>
492
493For template blocks
494~~~~~~~~~~~~~~~~~~~
495
496To control auto-escaping for a template, wrap the template (or just a
497particular section of the template) in the ``autoescape`` tag, like so::
498
499    {% autoescape off %}
500        Hello {{ name }}
501    {% endautoescape %}
502
503The ``autoescape`` tag takes either ``on`` or ``off`` as its argument. At
504times, you might want to force auto-escaping when it would otherwise be
505disabled. Here is an example template::
506
507    Auto-escaping is on by default. Hello {{ name }}
508
509    {% autoescape off %}
510        This will not be auto-escaped: {{ data }}.
511
512        Nor this: {{ other_data }}
513        {% autoescape on %}
514            Auto-escaping applies again: {{ name }}
515        {% endautoescape %}
516    {% endautoescape %}
517
518The auto-escaping tag passes its effect onto templates that extend the
519current one as well as templates included via the ``include`` tag, just like
520all block tags. For example::
521
522    # base.html
523
524    {% autoescape off %}
525    <h1>{% block title %}{% endblock %}</h1>
526    {% block content %}
527    {% endblock %}
528    {% endautoescape %}
529
530
531    # child.html
532
533    {% extends "base.html" %}
534    {% block title %}This & that{% endblock %}
535    {% block content %}{{ greeting }}{% endblock %}
536
537Because auto-escaping is turned off in the base template, it will also be
538turned off in the child template, resulting in the following rendered
539HTML when the ``greeting`` variable contains the string ``<b>Hello!</b>``::
540
541    <h1>This & that</h1>
542    <b>Hello!</b>
543
544Notes
545-----
546
547Generally, template authors don't need to worry about auto-escaping very much.
548Developers on the Python side (people writing views and custom filters) need to
549think about the cases in which data shouldn't be escaped, and mark data
550appropriately, so things Just Work in the template.
551
552If you're creating a template that might be used in situations where you're
553not sure whether auto-escaping is enabled, then add an ``escape`` filter to any
554variable that needs escaping. When auto-escaping is on, there's no danger of
555the ``escape`` filter *double-escaping* data -- the ``escape`` filter does not
556affect auto-escaped variables.
557
558String literals and automatic escaping
559--------------------------------------
560
561As we mentioned earlier, filter arguments can be strings::
562
563    {{ data|default:"This is a string literal." }}
564
565All string literals are inserted **without** any automatic escaping into the
566template -- they act as if they were all passed through the ``safe`` filter.
567The reasoning behind this is that the template author is in control of what
568goes into the string literal, so they can make sure the text is correctly
569escaped when the template is written.
570
571This means you would write ::
572
573    {{ data|default:"3 &lt; 2" }}
574
575...rather than ::
576
577    {{ data|default:"3 < 2" }}  <-- Bad! Don't do this.
578
579This doesn't affect what happens to data coming from the variable itself.
580The variable's contents are still automatically escaped, if necessary, because
581they're beyond the control of the template author.
582
583.. _template-accessing-methods:
584
585Accessing method calls
586======================
587
588Most method calls attached to objects are also available from within templates.
589This means that templates have access to much more than just class attributes
590(like field names) and variables passed in from views. For example, the Django
591ORM provides the :ref:`"entry_set"<topics-db-queries-related>` syntax for
592finding a collection of objects related on a foreign key. Therefore, given
593a model called "comment" with a foreign key relationship to a model called
594"task" you can loop through all comments attached to a given task like this::
595
596    {% for comment in task.comment_set.all %}
597        {{ comment }}
598    {% endfor %}
599
600Similarly, :doc:`QuerySets</ref/models/querysets>` provide a ``count()`` method
601to count the number of objects they contain. Therefore, you can obtain a count
602of all comments related to the current task with::
603
604    {{ task.comment_set.all.count }}
605
606And of course you can easily access methods you've explicitly defined on your
607own models::
608
609    # In model
610    class Task(models.Model):
611        def foo(self):
612            return "bar"
613
614    # In template
615    {{ task.foo }}
616
617Because Django intentionally limits the amount of logic processing available
618in the template language, it is not possible to pass arguments to method calls
619accessed from within templates. Data should be calculated in views, then passed
620to templates for display.
621
622.. _loading-custom-template-libraries:
623
624Custom tag and filter libraries
625===============================
626
627Certain applications provide custom tag and filter libraries. To access them in
628a template, use the ``{% load %}`` tag::
629
630    {% load comments %}
631
632    {% comment_form for blogs.entries entry.id with is_public yes %}
633
634In the above, the ``load`` tag loads the ``comments`` tag library, which then
635makes the ``comment_form`` tag available for use. Consult the documentation
636area in your admin to find the list of custom libraries in your installation.
637
638The ``{% load %}`` tag can take multiple library names, separated by spaces.
639Example::
640
641    {% load comments i18n %}
642
643See :doc:`/howto/custom-template-tags` for information on writing your own custom
644template libraries.
645
646Custom libraries and template inheritance
647-----------------------------------------
648
649When you load a custom tag or filter library, the tags/filters are only made
650available to the current template -- not any parent or child templates along
651the template-inheritance path.
652
653For example, if a template ``foo.html`` has ``{% load comments %}``, a child
654template (e.g., one that has ``{% extends "foo.html" %}``) will *not* have
655access to the comments template tags and filters. The child template is
656responsible for its own ``{% load comments %}``.
657
658This is a feature for the sake of maintainability and sanity.