2
0

language.txt 27 KB

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