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