PageRenderTime 67ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/docs/topics/templates.txt

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