templates.txt 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  1. .. _topics-templates:
  2. ============================
  3. The Django template language
  4. ============================
  5. .. admonition:: About this document
  6. This document explains the language syntax of the Django template system. If
  7. you're looking for a more technical perspective on how it works and how to
  8. extend it, see :ref:`ref-templates-api`.
  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 CheetahTemplate_, you should feel right at home with Django's templates.
  13. .. admonition:: Philosophy
  14. If you have a background in programming, or if you're used to languages
  15. like PHP which mix programming code directly into HTML, you'll want to
  16. bear in mind that the Django template system is not simply Python embedded
  17. into HTML. This is by design: the template system is meant to express
  18. presentation, not program logic.
  19. The Django template system provides tags which function similarly to some
  20. programming constructs -- an :ttag:`if` tag for boolean tests, a :ttag:`for`
  21. tag for looping, etc. -- but these are not simply executed as the
  22. corresponding Python code, and the template system will not execute
  23. arbitrary Python expressions. Only the tags, filters and syntax listed below
  24. are supported by default (although you can add :ref:`your own extensions
  25. <howto-custom-template-tags>` to the template language as needed).
  26. .. _`The Django template language: For Python programmers`: ../templates_python/
  27. .. _Smarty: http://smarty.php.net/
  28. .. _CheetahTemplate: http://www.cheetahtemplate.org/
  29. Templates
  30. =========
  31. .. highlightlang:: html+django
  32. A template is simply a text file. It can generate any text-based format (HTML,
  33. XML, CSV, etc.).
  34. A template contains **variables**, which get replaced with values when the
  35. template is evaluated, and **tags**, which control the logic of the template.
  36. Below is a minimal template that illustrates a few basics. Each element will be
  37. explained later in this document.::
  38. {% extends "base_generic.html" %}
  39. {% block title %}{{ section.title }}{% endblock %}
  40. {% block content %}
  41. <h1>{{ section.title }}</h1>
  42. {% for story in story_list %}
  43. <h2>
  44. <a href="{{ story.get_absolute_url }}">
  45. {{ story.headline|upper }}
  46. </a>
  47. </h2>
  48. <p>{{ story.tease|truncatewords:"100" }}</p>
  49. {% endfor %}
  50. {% endblock %}
  51. .. admonition:: Philosophy
  52. Why use a text-based template instead of an XML-based one (like Zope's
  53. TAL)? We wanted Django's template language to be usable for more than
  54. just XML/HTML templates. At World Online, we use it for e-mails,
  55. JavaScript and CSV. You can use the template language for any text-based
  56. format.
  57. Oh, and one more thing: Making humans edit XML is sadistic!
  58. Variables
  59. =========
  60. Variables look like this: ``{{ variable }}``. When the template engine
  61. encounters a variable, it evaluates that variable and replaces it with the
  62. result.
  63. Use a dot (``.``) to access attributes of a variable.
  64. .. admonition:: Behind the scenes
  65. Technically, when the template system encounters a dot, it tries the
  66. following lookups, in this order:
  67. * Dictionary lookup
  68. * Attribute lookup
  69. * Method call
  70. * List-index lookup
  71. In the above example, ``{{ section.title }}`` will be replaced with the
  72. ``title`` attribute of the ``section`` object.
  73. If you use a variable that doesn't exist, the template system will insert
  74. the value of the ``TEMPLATE_STRING_IF_INVALID`` setting, which is set to ``''``
  75. (the empty string) by default.
  76. See `Using the built-in reference`_, below, for help on finding what variables
  77. are available in a given template.
  78. Filters
  79. =======
  80. You can modify variables for display by using **filters**.
  81. Filters look like this: ``{{ name|lower }}``. This displays the value of the
  82. ``{{ name }}`` variable after being filtered through the ``lower`` filter,
  83. which converts text to lowercase. Use a pipe (``|``) to apply a filter.
  84. Filters can be "chained." The output of one filter is applied to the next.
  85. ``{{ text|escape|linebreaks }}`` is a common idiom for escaping text contents,
  86. then converting line breaks to ``<p>`` tags.
  87. Some filters take arguments. A filter argument looks like this: ``{{
  88. bio|truncatewords:30 }}``. This will display the first 30 words of the ``bio``
  89. variable.
  90. Filter arguments that contain spaces must be quoted; for example, to join a list
  91. with commas and spaced you'd use ``{{ list|join:", " }}``.
  92. Django provides about thirty built-in template filters. You can read all about
  93. them in the :ref:`built-in filter reference <ref-templates-builtins-filters>`.
  94. To give you a taste of what's available, here are some of the more commonly used
  95. template filters:
  96. :tfilter:`default`
  97. If a variable is false or empty, use given default. Otherwise, use the
  98. value of the variable
  99. For example::
  100. {{ value|default:"nothing" }}
  101. If ``value`` isn't provided or is empty, the above will display
  102. "``nothing``".
  103. :tfilter:`length`
  104. Returns the length of the value. This works for both strings and lists;
  105. for example::
  106. {{ value|length }}
  107. If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``4``.
  108. :tfilter:`striptags`
  109. Strips all [X]HTML tags. For example::
  110. {{ value|striptags }}
  111. If ``value`` is ``"<b>Joel</b> <button>is</button> a
  112. <span>slug</span>"``, the output will be ``"Joel is a slug"``.
  113. Again, these are just a few examples; see the :ref:`built-in filter reference
  114. <ref-templates-builtins-filters>` for the complete list.
  115. You can also create your own custom template filters; see
  116. :ref:`howto-custom-template-tags`.
  117. Tags
  118. ====
  119. Tags look like this: ``{% tag %}``. Tags are more complex than variables: Some
  120. create text in the output, some control flow by performing loops or logic, and
  121. some load external information into the template to be used by later variables.
  122. Some tags require beginning and ending tags (i.e. ``{% tag %} ... tag contents
  123. ... {% endtag %}``).
  124. Django ships with about two dozen built-in template tags. You can read all about
  125. them in the :ref:`built-in tag reference <ref-templates-builtins-tags>`. To give
  126. you a taste of what's available, here are some of the more commonly used
  127. tags:
  128. :ttag:`for`
  129. Loop over each item in an array. For example, to display a list of athletes
  130. provided in ``athlete_list``::
  131. <ul>
  132. {% for athlete in athlete_list %}
  133. <li>{{ athlete.name }}</li>
  134. {% endfor %}
  135. </ul>
  136. :ttag:`if` and :ttag:`else`
  137. Evaluates a variable, and if that variable is "true" the contents of the
  138. block are displayed::
  139. {% if athlete_list %}
  140. Number of athletes: {{ athlete_list|length }}
  141. {% else %}
  142. No athletes.
  143. {% endif %}
  144. In the above, if ``athlete_list`` is not empty, the number of athletes
  145. will be displayed by the ``{{ athlete_list|length }}`` variable.
  146. :ttag:`ifequal` and :ttag:`ifnotequal`
  147. Display some contents if two arguments are or are not equal. For example::
  148. {% ifequal athlete.name coach.name %}
  149. ...
  150. {% endifequal %}
  151. Or::
  152. {% ifnotequal athlete.name "Joe" %}
  153. ...
  154. {% endifnotequal %}
  155. :ttag:`block` and :ttag:`extends`
  156. Set up `template inheritance`_ (see below), a powerful way
  157. of cutting down on "boilerplate" in templates.
  158. Again, the above is only a selection of the whole list; see the :ref:`built-in
  159. tag reference <ref-templates-builtins-tags>` for the complete list.
  160. You can also create your own custom template tags; see
  161. :ref:`howto-custom-template-tags`.
  162. Comments
  163. ========
  164. To comment-out part of a line in a template, use the comment syntax: ``{# #}``.
  165. For example, this template would render as ``'hello'``::
  166. {# greeting #}hello
  167. A comment can contain any template code, invalid or not. For example::
  168. {# {% if foo %}bar{% else %} #}
  169. This syntax can only be used for single-line comments (no newlines are permitted
  170. between the ``{#`` and ``#}`` delimiters). If you need to comment out a
  171. multiline portion of the template, see the :ttag:`comment` tag.
  172. .. _template-inheritance:
  173. Template inheritance
  174. ====================
  175. The most powerful -- and thus the most complex -- part of Django's template
  176. engine is template inheritance. Template inheritance allows you to build a base
  177. "skeleton" template that contains all the common elements of your site and
  178. defines **blocks** that child templates can override.
  179. It's easiest to understand template inheritance by starting with an example::
  180. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  181. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  182. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  183. <head>
  184. <link rel="stylesheet" href="style.css" />
  185. <title>{% block title %}My amazing site{% endblock %}</title>
  186. </head>
  187. <body>
  188. <div id="sidebar">
  189. {% block sidebar %}
  190. <ul>
  191. <li><a href="/">Home</a></li>
  192. <li><a href="/blog/">Blog</a></li>
  193. </ul>
  194. {% endblock %}
  195. </div>
  196. <div id="content">
  197. {% block content %}{% endblock %}
  198. </div>
  199. </body>
  200. </html>
  201. This template, which we'll call ``base.html``, defines a simple HTML skeleton
  202. document that you might use for a simple two-column page. It's the job of
  203. "child" templates to fill the empty blocks with content.
  204. In this example, the ``{% block %}`` tag defines three blocks that child
  205. templates can fill in. All the ``block`` tag does is to tell the template
  206. engine that a child template may override those portions of the template.
  207. A child template might look like this::
  208. {% extends "base.html" %}
  209. {% block title %}My amazing blog{% endblock %}
  210. {% block content %}
  211. {% for entry in blog_entries %}
  212. <h2>{{ entry.title }}</h2>
  213. <p>{{ entry.body }}</p>
  214. {% endfor %}
  215. {% endblock %}
  216. The ``{% extends %}`` tag is the key here. It tells the template engine that
  217. this template "extends" another template. When the template system evaluates
  218. this template, first it locates the parent -- in this case, "base.html".
  219. At that point, the template engine will notice the three ``{% block %}`` tags
  220. in ``base.html`` and replace those blocks with the contents of the child
  221. template. Depending on the value of ``blog_entries``, the output might look
  222. like::
  223. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  224. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  225. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  226. <head>
  227. <link rel="stylesheet" href="style.css" />
  228. <title>My amazing blog</title>
  229. </head>
  230. <body>
  231. <div id="sidebar">
  232. <ul>
  233. <li><a href="/">Home</a></li>
  234. <li><a href="/blog/">Blog</a></li>
  235. </ul>
  236. </div>
  237. <div id="content">
  238. <h2>Entry one</h2>
  239. <p>This is my first entry.</p>
  240. <h2>Entry two</h2>
  241. <p>This is my second entry.</p>
  242. </div>
  243. </body>
  244. </html>
  245. Note that since the child template didn't define the ``sidebar`` block, the
  246. value from the parent template is used instead. Content within a ``{% block %}``
  247. tag in a parent template is always used as a fallback.
  248. You can use as many levels of inheritance as needed. One common way of using
  249. inheritance is the following three-level approach:
  250. * Create a ``base.html`` template that holds the main look-and-feel of your
  251. site.
  252. * Create a ``base_SECTIONNAME.html`` template for each "section" of your
  253. site. For example, ``base_news.html``, ``base_sports.html``. These
  254. templates all extend ``base.html`` and include section-specific
  255. styles/design.
  256. * Create individual templates for each type of page, such as a news
  257. article or blog entry. These templates extend the appropriate section
  258. template.
  259. This approach maximizes code reuse and makes it easy to add items to shared
  260. content areas, such as section-wide navigation.
  261. Here are some tips for working with inheritance:
  262. * If you use ``{% extends %}`` in a template, it must be the first template
  263. tag in that template. Template inheritance won't work, otherwise.
  264. * More ``{% block %}`` tags in your base templates are better. Remember,
  265. child templates don't have to define all parent blocks, so you can fill
  266. in reasonable defaults in a number of blocks, then only define the ones
  267. you need later. It's better to have more hooks than fewer hooks.
  268. * If you find yourself duplicating content in a number of templates, it
  269. probably means you should move that content to a ``{% block %}`` in a
  270. parent template.
  271. * If you need to get the content of the block from the parent template,
  272. the ``{{ block.super }}`` variable will do the trick. This is useful
  273. if you want to add to the contents of a parent block instead of
  274. completely overriding it. Data inserted using ``{{ block.super }}`` will
  275. not be automatically escaped (see the `next section`_), since it was
  276. already escaped, if necessary, in the parent template.
  277. * For extra readability, you can optionally give a *name* to your
  278. ``{% endblock %}`` tag. For example::
  279. {% block content %}
  280. ...
  281. {% endblock content %}
  282. In larger templates, this technique helps you see which ``{% block %}``
  283. tags are being closed.
  284. Finally, note that you can't define multiple ``{% block %}`` tags with the same
  285. name in the same template. This limitation exists because a block tag works in
  286. "both" directions. That is, a block tag doesn't just provide a hole to fill --
  287. it also defines the content that fills the hole in the *parent*. If there were
  288. two similarly-named ``{% block %}`` tags in a template, that template's parent
  289. wouldn't know which one of the blocks' content to use.
  290. .. _next section: #automatic-html-escaping
  291. .. _automatic-html-escaping:
  292. Automatic HTML escaping
  293. =======================
  294. .. versionadded:: 1.0
  295. When generating HTML from templates, there's always a risk that a variable will
  296. include characters that affect the resulting HTML. For example, consider this
  297. template fragment::
  298. Hello, {{ name }}.
  299. At first, this seems like a harmless way to display a user's name, but consider
  300. what would happen if the user entered his name as this::
  301. <script>alert('hello')</script>
  302. With this name value, the template would be rendered as::
  303. Hello, <script>alert('hello')</script>
  304. ...which means the browser would pop-up a JavaScript alert box!
  305. Similarly, what if the name contained a ``'<'`` symbol, like this?
  306. <b>username
  307. That would result in a rendered template like this::
  308. Hello, <b>username
  309. ...which, in turn, would result in the remainder of the Web page being bolded!
  310. Clearly, user-submitted data shouldn't be trusted blindly and inserted directly
  311. into your Web pages, because a malicious user could use this kind of hole to
  312. do potentially bad things. This type of security exploit is called a
  313. `Cross Site Scripting`_ (XSS) attack.
  314. To avoid this problem, you have two options:
  315. * One, you can make sure to run each untrusted variable through the
  316. ``escape`` filter (documented below), which converts potentially harmful
  317. HTML characters to unharmful ones. This was the default solution
  318. in Django for its first few years, but the problem is that it puts the
  319. onus on *you*, the developer / template author, to ensure you're escaping
  320. everything. It's easy to forget to escape data.
  321. * Two, you can take advantage of Django's automatic HTML escaping. The
  322. remainder of this section describes how auto-escaping works.
  323. By default in the Django development version, every template automatically
  324. escapes the output of every variable tag. Specifically, these five characters
  325. are escaped:
  326. * ``<`` is converted to ``&lt;``
  327. * ``>`` is converted to ``&gt;``
  328. * ``'`` (single quote) is converted to ``&#39;``
  329. * ``"`` (double quote) is converted to ``&quot;``
  330. * ``&`` is converted to ``&amp;``
  331. Again, we stress that this behavior is on by default. If you're using Django's
  332. template system, you're protected.
  333. .. _Cross Site Scripting: http://en.wikipedia.org/wiki/Cross-site_scripting
  334. How to turn it off
  335. ------------------
  336. If you don't want data to be auto-escaped, on a per-site, per-template level or
  337. per-variable level, you can turn it off in several ways.
  338. Why would you want to turn it off? Because sometimes, template variables
  339. contain data that you *intend* to be rendered as raw HTML, in which case you
  340. don't want their contents to be escaped. For example, you might store a blob of
  341. HTML in your database and want to embed that directly into your template. Or,
  342. you might be using Django's template system to produce text that is *not* HTML
  343. -- like an e-mail message, for instance.
  344. For individual variables
  345. ~~~~~~~~~~~~~~~~~~~~~~~~
  346. To disable auto-escaping for an individual variable, use the ``safe`` filter::
  347. This will be escaped: {{ data }}
  348. This will not be escaped: {{ data|safe }}
  349. Think of *safe* as shorthand for *safe from further escaping* or *can be
  350. safely interpreted as HTML*. In this example, if ``data`` contains ``'<b>'``,
  351. the output will be::
  352. This will be escaped: &lt;b&gt;
  353. This will not be escaped: <b>
  354. For template blocks
  355. ~~~~~~~~~~~~~~~~~~~
  356. To control auto-escaping for a template, wrap the template (or just a
  357. particular section of the template) in the ``autoescape`` tag, like so::
  358. {% autoescape off %}
  359. Hello {{ name }}
  360. {% endautoescape %}
  361. The ``autoescape`` tag takes either ``on`` or ``off`` as its argument. At
  362. times, you might want to force auto-escaping when it would otherwise be
  363. disabled. Here is an example template::
  364. Auto-escaping is on by default. Hello {{ name }}
  365. {% autoescape off %}
  366. This will not be auto-escaped: {{ data }}.
  367. Nor this: {{ other_data }}
  368. {% autoescape on %}
  369. Auto-escaping applies again: {{ name }}
  370. {% endautoescape %}
  371. {% endautoescape %}
  372. The auto-escaping tag passes its effect onto templates that extend the
  373. current one as well as templates included via the ``include`` tag, just like
  374. all block tags. For example::
  375. # base.html
  376. {% autoescape off %}
  377. <h1>{% block title %}{% endblock %}</h1>
  378. {% block content %}
  379. {% endblock %}
  380. {% endautoescape %}
  381. # child.html
  382. {% extends "base.html" %}
  383. {% block title %}This & that{% endblock %}
  384. {% block content %}{{ greeting }}{% endblock %}
  385. Because auto-escaping is turned off in the base template, it will also be
  386. turned off in the child template, resulting in the following rendered
  387. HTML when the ``greeting`` variable contains the string ``<b>Hello!</b>``::
  388. <h1>This & that</h1>
  389. <b>Hello!</b>
  390. Notes
  391. -----
  392. Generally, template authors don't need to worry about auto-escaping very much.
  393. Developers on the Python side (people writing views and custom filters) need to
  394. think about the cases in which data shouldn't be escaped, and mark data
  395. appropriately, so things Just Work in the template.
  396. If you're creating a template that might be used in situations where you're
  397. not sure whether auto-escaping is enabled, then add an ``escape`` filter to any
  398. variable that needs escaping. When auto-escaping is on, there's no danger of
  399. the ``escape`` filter *double-escaping* data -- the ``escape`` filter does not
  400. affect auto-escaped variables.
  401. String literals and automatic escaping
  402. --------------------------------------
  403. As we mentioned earlier, filter arguments can be strings::
  404. {{ data|default:"This is a string literal." }}
  405. All string literals are inserted **without** any automatic escaping into the
  406. template -- they act as if they were all passed through the ``safe`` filter.
  407. The reasoning behind this is that the template author is in control of what
  408. goes into the string literal, so they can make sure the text is correctly
  409. escaped when the template is written.
  410. This means you would write ::
  411. {{ data|default:"3 &lt; 2" }}
  412. ...rather than ::
  413. {{ data|default:"3 < 2" }} <-- Bad! Don't do this.
  414. This doesn't affect what happens to data coming from the variable itself.
  415. The variable's contents are still automatically escaped, if necessary, because
  416. they're beyond the control of the template author.
  417. .. _template-built-in-reference:
  418. Using the built-in reference
  419. ============================
  420. Django's admin interface includes a complete reference of all template tags and
  421. filters available for a given site. To see it, go to your admin interface and
  422. click the "Documentation" link in the upper right of the page.
  423. The reference is divided into 4 sections: tags, filters, models, and views.
  424. The **tags** and **filters** sections describe all the built-in tags (in fact,
  425. the tag and filter references below come directly from those pages) as well as
  426. any custom tag or filter libraries available.
  427. The **views** page is the most valuable. Each URL in your site has a separate
  428. entry here, and clicking on a URL will show you:
  429. * The name of the view function that generates that view.
  430. * A short description of what the view does.
  431. * The **context**, or a list of variables available in the view's template.
  432. * The name of the template or templates that are used for that view.
  433. Each view documentation page also has a bookmarklet that you can use to jump
  434. from any page to the documentation page for that view.
  435. Because Django-powered sites usually use database objects, the **models**
  436. section of the documentation page describes each type of object in the system
  437. along with all the fields available on that object.
  438. Taken together, the documentation pages should tell you every tag, filter,
  439. variable and object available to you in a given template.
  440. .. _loading-custom-template-libraries:
  441. Custom tag and filter libraries
  442. ===============================
  443. Certain applications provide custom tag and filter libraries. To access them in
  444. a template, use the ``{% load %}`` tag::
  445. {% load comments %}
  446. {% comment_form for blogs.entries entry.id with is_public yes %}
  447. In the above, the ``load`` tag loads the ``comments`` tag library, which then
  448. makes the ``comment_form`` tag available for use. Consult the documentation
  449. area in your admin to find the list of custom libraries in your installation.
  450. The ``{% load %}`` tag can take multiple library names, separated by spaces.
  451. Example::
  452. {% load comments i18n %}
  453. See :ref:`howto-custom-template-tags` for information on writing your own custom
  454. template libraries.
  455. Custom libraries and template inheritance
  456. -----------------------------------------
  457. When you load a custom tag or filter library, the tags/filters are only made
  458. available to the current template -- not any parent or child templates along
  459. the template-inheritance path.
  460. For example, if a template ``foo.html`` has ``{% load comments %}``, a child
  461. template (e.g., one that has ``{% extends "foo.html" %}``) will *not* have
  462. access to the comments template tags and filters. The child template is
  463. responsible for its own ``{% load comments %}``.
  464. This is a feature for the sake of maintainability and sanity.