PageRenderTime 59ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/docs/ref/templates/builtins.txt

https://code.google.com/p/mango-py/
Plain Text | 2281 lines | 1522 code | 759 blank | 0 comment | 0 complexity | 10700e293992cc83de86f42883c27609 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. ==================================
  2. Built-in template tags and filters
  3. ==================================
  4. This document describes Django's built-in template tags and filters. It is
  5. recommended that you use the :doc:`automatic documentation
  6. </ref/contrib/admin/admindocs>`, if available, as this will also include
  7. documentation for any custom tags or filters installed.
  8. .. _ref-templates-builtins-tags:
  9. Built-in tag reference
  10. ----------------------
  11. .. highlightlang:: html+django
  12. .. templatetag:: autoescape
  13. autoescape
  14. ~~~~~~~~~~
  15. Control the current auto-escaping behavior. This tag takes either ``on`` or
  16. ``off`` as an argument and that determines whether auto-escaping is in effect
  17. inside the block. The block is closed with an ``endautoescape`` ending tag.
  18. When auto-escaping is in effect, all variable content has HTML escaping applied
  19. to it before placing the result into the output (but after any filters have
  20. been applied). This is equivalent to manually applying the ``escape`` filter
  21. to each variable.
  22. The only exceptions are variables that are already marked as "safe" from
  23. escaping, either by the code that populated the variable, or because it has had
  24. the ``safe`` or ``escape`` filters applied.
  25. Sample usage::
  26. {% autoescape on %}
  27. {{ body }}
  28. {% endautoescape %}
  29. .. templatetag:: block
  30. block
  31. ~~~~~
  32. Define a block that can be overridden by child templates. See
  33. :ref:`Template inheritance <template-inheritance>` for more information.
  34. .. templatetag:: comment
  35. comment
  36. ~~~~~~~
  37. Ignore everything between ``{% comment %}`` and ``{% endcomment %}``
  38. .. templatetag:: csrf_token
  39. csrf_token
  40. ~~~~~~~~~~
  41. In the Django 1.1.X series, this is a no-op tag that returns an empty string for
  42. future compatibility purposes. In Django 1.2 and later, it is used for CSRF
  43. protection, as described in the documentation for :doc:`Cross Site Request
  44. Forgeries </ref/contrib/csrf>`.
  45. .. templatetag:: cycle
  46. cycle
  47. ~~~~~
  48. Cycle among the given strings or variables each time this tag is encountered.
  49. Within a loop, cycles among the given strings each time through the
  50. loop::
  51. {% for o in some_list %}
  52. <tr class="{% cycle 'row1' 'row2' %}">
  53. ...
  54. </tr>
  55. {% endfor %}
  56. You can use variables, too. For example, if you have two template variables,
  57. ``rowvalue1`` and ``rowvalue2``, you can cycle between their values like this::
  58. {% for o in some_list %}
  59. <tr class="{% cycle rowvalue1 rowvalue2 %}">
  60. ...
  61. </tr>
  62. {% endfor %}
  63. Yes, you can mix variables and strings::
  64. {% for o in some_list %}
  65. <tr class="{% cycle 'row1' rowvalue2 'row3' %}">
  66. ...
  67. </tr>
  68. {% endfor %}
  69. In some cases you might want to refer to the next value of a cycle from
  70. outside of a loop. To do this, just give the ``{% cycle %}`` tag a name, using
  71. "as", like this::
  72. {% cycle 'row1' 'row2' as rowcolors %}
  73. From then on, you can insert the current value of the cycle wherever
  74. you'd like in your template by referencing the cycle name as a context
  75. variable. If you want to move the cycle onto the next value, you use
  76. the cycle tag again, using the name of the variable. So, the following
  77. template::
  78. <tr>
  79. <td class="{% cycle 'row1' 'row2' as rowcolors %}">...</td>
  80. <td class="{{ rowcolors }}">...</td>
  81. </tr>
  82. <tr>
  83. <td class="{% cycle rowcolors %}">...</td>
  84. <td class="{{ rowcolors }}">...</td>
  85. </tr>
  86. would output::
  87. <tr>
  88. <td class="row1">...</td>
  89. <td class="row1">...</td>
  90. </tr>
  91. <tr>
  92. <td class="row2">...</td>
  93. <td class="row2">...</td>
  94. </tr>
  95. You can use any number of values in a ``{% cycle %}`` tag, separated by spaces.
  96. Values enclosed in single (``'``) or double quotes (``"``) are treated as
  97. string literals, while values without quotes are treated as template variables.
  98. Note that the variables included in the cycle will not be escaped.
  99. This is because template tags do not escape their content. Any HTML or
  100. Javascript code contained in the printed variable will be rendered
  101. as-is, which could potentially lead to security issues.
  102. If you need to escape the variables in the cycle, you must do so
  103. explicitly::
  104. {% filter force_escape %}
  105. {% cycle var1 var2 var3 %}
  106. {% endfilter %}
  107. For backwards compatibility, the ``{% cycle %}`` tag supports the much inferior
  108. old syntax from previous Django versions. You shouldn't use this in any new
  109. projects, but for the sake of the people who are still using it, here's what it
  110. looks like::
  111. {% cycle row1,row2,row3 %}
  112. In this syntax, each value gets interpreted as a literal string, and there's no
  113. way to specify variable values. Or literal commas. Or spaces. Did we mention
  114. you shouldn't use this syntax in any new projects?
  115. .. versionadded:: 1.3
  116. By default, when you use the ``as`` keyword with the cycle tag, the
  117. usage of ``{% cycle %}`` that declares the cycle will itself output
  118. the first value in the cycle. This could be a problem if you want to
  119. use the value in a nested loop or an included template. If you want to
  120. just declare the cycle, but not output the first value, you can add a
  121. ``silent`` keyword as the last keyword in the tag. For example::
  122. {% for obj in some_list %}
  123. {% cycle 'row1' 'row2' as rowcolors silent %}
  124. <tr class="{{ rowcolors }}">{% include "subtemplate.html " %}</tr>
  125. {% endfor %}
  126. This will output a list of ``<tr>`` elements with ``class``
  127. alternating between ``row1`` and ``row2``; the subtemplate will have
  128. access to ``rowcolors`` in it's context that matches the class of the
  129. ``<tr>`` that encloses it. If the ``silent`` keyword were to be
  130. omitted, ``row1`` would be emitted as normal text, outside the
  131. ``<tr>`` element.
  132. When the silent keyword is used on a cycle definition, the silence
  133. automatically applies to all subsequent uses of the cycle tag. In,
  134. the following template would output *nothing*, even though the second
  135. call to ``{% cycle %}`` doesn't specify silent::
  136. {% cycle 'row1' 'row2' as rowcolors silent %}
  137. {% cycle rowcolors %}
  138. .. templatetag:: debug
  139. debug
  140. ~~~~~
  141. Output a whole load of debugging information, including the current context and
  142. imported modules.
  143. .. templatetag:: extends
  144. extends
  145. ~~~~~~~
  146. Signal that this template extends a parent template.
  147. This tag can be used in two ways:
  148. * ``{% extends "base.html" %}`` (with quotes) uses the literal value
  149. ``"base.html"`` as the name of the parent template to extend.
  150. * ``{% extends variable %}`` uses the value of ``variable``. If the variable
  151. evaluates to a string, Django will use that string as the name of the
  152. parent template. If the variable evaluates to a ``Template`` object,
  153. Django will use that object as the parent template.
  154. See :ref:`template-inheritance` for more information.
  155. .. templatetag:: filter
  156. filter
  157. ~~~~~~
  158. Filter the contents of the variable through variable filters.
  159. Filters can also be piped through each other, and they can have arguments --
  160. just like in variable syntax.
  161. Sample usage::
  162. {% filter force_escape|lower %}
  163. This text will be HTML-escaped, and will appear in all lowercase.
  164. {% endfilter %}
  165. .. templatetag:: firstof
  166. firstof
  167. ~~~~~~~
  168. Outputs the first variable passed that is not False, without escaping.
  169. Outputs nothing if all the passed variables are False.
  170. Sample usage::
  171. {% firstof var1 var2 var3 %}
  172. This is equivalent to::
  173. {% if var1 %}
  174. {{ var1|safe }}
  175. {% else %}{% if var2 %}
  176. {{ var2|safe }}
  177. {% else %}{% if var3 %}
  178. {{ var3|safe }}
  179. {% endif %}{% endif %}{% endif %}
  180. You can also use a literal string as a fallback value in case all
  181. passed variables are False::
  182. {% firstof var1 var2 var3 "fallback value" %}
  183. Note that the variables included in the firstof tag will not be
  184. escaped. This is because template tags do not escape their content.
  185. Any HTML or Javascript code contained in the printed variable will be
  186. rendered as-is, which could potentially lead to security issues.
  187. If you need to escape the variables in the firstof tag, you must do so
  188. explicitly::
  189. {% filter force_escape %}
  190. {% firstof var1 var2 var3 "fallback value" %}
  191. {% endfilter %}
  192. .. templatetag:: for
  193. for
  194. ~~~
  195. Loop over each item in an array. For example, to display a list of athletes
  196. provided in ``athlete_list``::
  197. <ul>
  198. {% for athlete in athlete_list %}
  199. <li>{{ athlete.name }}</li>
  200. {% endfor %}
  201. </ul>
  202. You can loop over a list in reverse by using ``{% for obj in list reversed %}``.
  203. If you need to loop over a list of lists, you can unpack the values
  204. in each sub-list into individual variables. For example, if your context
  205. contains a list of (x,y) coordinates called ``points``, you could use the
  206. following to output the list of points::
  207. {% for x, y in points %}
  208. There is a point at {{ x }},{{ y }}
  209. {% endfor %}
  210. This can also be useful if you need to access the items in a dictionary.
  211. For example, if your context contained a dictionary ``data``, the following
  212. would display the keys and values of the dictionary::
  213. {% for key, value in data.items %}
  214. {{ key }}: {{ value }}
  215. {% endfor %}
  216. The for loop sets a number of variables available within the loop:
  217. ========================== ================================================
  218. Variable Description
  219. ========================== ================================================
  220. ``forloop.counter`` The current iteration of the loop (1-indexed)
  221. ``forloop.counter0`` The current iteration of the loop (0-indexed)
  222. ``forloop.revcounter`` The number of iterations from the end of the
  223. loop (1-indexed)
  224. ``forloop.revcounter0`` The number of iterations from the end of the
  225. loop (0-indexed)
  226. ``forloop.first`` True if this is the first time through the loop
  227. ``forloop.last`` True if this is the last time through the loop
  228. ``forloop.parentloop`` For nested loops, this is the loop "above" the
  229. current one
  230. ========================== ================================================
  231. for ... empty
  232. ^^^^^^^^^^^^^
  233. The ``for`` tag can take an optional ``{% empty %}`` clause that will be
  234. displayed if the given array is empty or could not be found::
  235. <ul>
  236. {% for athlete in athlete_list %}
  237. <li>{{ athlete.name }}</li>
  238. {% empty %}
  239. <li>Sorry, no athlete in this list!</li>
  240. {% endfor %}
  241. <ul>
  242. The above is equivalent to -- but shorter, cleaner, and possibly faster
  243. than -- the following::
  244. <ul>
  245. {% if athlete_list %}
  246. {% for athlete in athlete_list %}
  247. <li>{{ athlete.name }}</li>
  248. {% endfor %}
  249. {% else %}
  250. <li>Sorry, no athletes in this list.</li>
  251. {% endif %}
  252. </ul>
  253. .. templatetag:: if
  254. if
  255. ~~
  256. The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e.
  257. exists, is not empty, and is not a false boolean value) the contents of the
  258. block are output::
  259. {% if athlete_list %}
  260. Number of athletes: {{ athlete_list|length }}
  261. {% else %}
  262. No athletes.
  263. {% endif %}
  264. In the above, if ``athlete_list`` is not empty, the number of athletes will be
  265. displayed by the ``{{ athlete_list|length }}`` variable.
  266. As you can see, the ``if`` tag can take an optional ``{% else %}`` clause that
  267. will be displayed if the test fails.
  268. Boolean operators
  269. ^^^^^^^^^^^^^^^^^
  270. ``if`` tags may use ``and``, ``or`` or ``not`` to test a number of variables or
  271. to negate a given variable::
  272. {% if athlete_list and coach_list %}
  273. Both athletes and coaches are available.
  274. {% endif %}
  275. {% if not athlete_list %}
  276. There are no athletes.
  277. {% endif %}
  278. {% if athlete_list or coach_list %}
  279. There are some athletes or some coaches.
  280. {% endif %}
  281. {% if not athlete_list or coach_list %}
  282. There are no athletes or there are some coaches (OK, so
  283. writing English translations of boolean logic sounds
  284. stupid; it's not our fault).
  285. {% endif %}
  286. {% if athlete_list and not coach_list %}
  287. There are some athletes and absolutely no coaches.
  288. {% endif %}
  289. .. versionchanged:: 1.2
  290. Use of both ``and`` and ``or`` clauses within the same tag is allowed, with
  291. ``and`` having higher precedence than ``or`` e.g.::
  292. {% if athlete_list and coach_list or cheerleader_list %}
  293. will be interpreted like:
  294. .. code-block:: python
  295. if (athlete_list and coach_list) or cheerleader_list
  296. Use of actual brackets in the ``if`` tag is invalid syntax. If you need them to
  297. indicate precedence, you should use nested ``if`` tags.
  298. .. versionadded:: 1.2
  299. ``if`` tags may also use the operators ``==``, ``!=``, ``<``, ``>``,
  300. ``<=``, ``>=`` and ``in`` which work as follows:
  301. ``==`` operator
  302. ^^^^^^^^^^^^^^^
  303. Equality. Example::
  304. {% if somevar == "x" %}
  305. This appears if variable somevar equals the string "x"
  306. {% endif %}
  307. ``!=`` operator
  308. ^^^^^^^^^^^^^^^
  309. Inequality. Example::
  310. {% if somevar != "x" %}
  311. This appears if variable somevar does not equal the string "x",
  312. or if somevar is not found in the context
  313. {% endif %}
  314. ``<`` operator
  315. ^^^^^^^^^^^^^^
  316. Less than. Example::
  317. {% if somevar < 100 %}
  318. This appears if variable somevar is less than 100.
  319. {% endif %}
  320. ``>`` operator
  321. ^^^^^^^^^^^^^^
  322. Greater than. Example::
  323. {% if somevar > 0 %}
  324. This appears if variable somevar is greater than 0.
  325. {% endif %}
  326. ``<=`` operator
  327. ^^^^^^^^^^^^^^^
  328. Less than or equal to. Example::
  329. {% if somevar <= 100 %}
  330. This appears if variable somevar is less than 100 or equal to 100.
  331. {% endif %}
  332. ``>=`` operator
  333. ^^^^^^^^^^^^^^^
  334. Greater than or equal to. Example::
  335. {% if somevar >= 1 %}
  336. This appears if variable somevar is greater than 1 or equal to 1.
  337. {% endif %}
  338. ``in`` operator
  339. ^^^^^^^^^^^^^^^
  340. Contained within. This operator is supported by many Python containers to test
  341. whether the given value is in the container. The following are some examples of
  342. how ``x in y`` will be interpreted::
  343. {% if "bc" in "abcdef" %}
  344. This appears since "bc" is a substring of "abcdef"
  345. {% endif %}
  346. {% if "hello" in greetings %}
  347. If greetings is a list or set, one element of which is the string
  348. "hello", this will appear.
  349. {% endif %}
  350. {% if user in users %}
  351. If users is a QuerySet, this will appear if user is an
  352. instance that belongs to the QuerySet.
  353. {% endif %}
  354. ``not in`` operator
  355. ~~~~~~~~~~~~~~~~~~~~
  356. Not contained within. This is the negation of the ``in`` operator.
  357. The comparison operators cannot be 'chained' like in Python or in mathematical
  358. notation. For example, instead of using::
  359. {% if a > b > c %} (WRONG)
  360. you should use::
  361. {% if a > b and b > c %}
  362. Filters
  363. ^^^^^^^
  364. You can also use filters in the ``if`` expression. For example::
  365. {% if messages|length >= 100 %}
  366. You have lots of messages today!
  367. {% endif %}
  368. Complex expressions
  369. ^^^^^^^^^^^^^^^^^^^
  370. All of the above can be combined to form complex expressions. For such
  371. expressions, it can be important to know how the operators are grouped when the
  372. expression is evaluated - that is, the precedence rules. The precedence of the
  373. operators, from lowest to highest, is as follows:
  374. * ``or``
  375. * ``and``
  376. * ``not``
  377. * ``in``
  378. * ``==``, ``!=``, ``<``, ``>``,``<=``, ``>=``
  379. (This follows Python exactly). So, for example, the following complex if tag:
  380. .. code-block:: django
  381. {% if a == b or c == d and e %}
  382. ...will be interpreted as:
  383. .. code-block:: python
  384. (a == b) or ((c == d) and e)
  385. If you need different precedence, you will need to use nested if tags. Sometimes
  386. that is better for clarity anyway, for the sake of those who do not know the
  387. precedence rules.
  388. .. templatetag:: ifchanged
  389. ifchanged
  390. ~~~~~~~~~
  391. Check if a value has changed from the last iteration of a loop.
  392. The 'ifchanged' block tag is used within a loop. It has two possible uses.
  393. 1. Checks its own rendered contents against its previous state and only
  394. displays the content if it has changed. For example, this displays a list of
  395. days, only displaying the month if it changes::
  396. <h1>Archive for {{ year }}</h1>
  397. {% for date in days %}
  398. {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
  399. <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
  400. {% endfor %}
  401. 2. If given a variable, check whether that variable has changed. For
  402. example, the following shows the date every time it changes, but
  403. only shows the hour if both the hour and the date has changed::
  404. {% for date in days %}
  405. {% ifchanged date.date %} {{ date.date }} {% endifchanged %}
  406. {% ifchanged date.hour date.date %}
  407. {{ date.hour }}
  408. {% endifchanged %}
  409. {% endfor %}
  410. The ``ifchanged`` tag can also take an optional ``{% else %}`` clause that
  411. will be displayed if the value has not changed::
  412. {% for match in matches %}
  413. <div style="background-color:
  414. {% ifchanged match.ballot_id %}
  415. {% cycle "red" "blue" %}
  416. {% else %}
  417. grey
  418. {% endifchanged %}
  419. ">{{ match }}</div>
  420. {% endfor %}
  421. .. templatetag:: ifequal
  422. ifequal
  423. ~~~~~~~
  424. Output the contents of the block if the two arguments equal each other.
  425. Example::
  426. {% ifequal user.id comment.user_id %}
  427. ...
  428. {% endifequal %}
  429. As in the ``{% if %}`` tag, an ``{% else %}`` clause is optional.
  430. The arguments can be hard-coded strings, so the following is valid::
  431. {% ifequal user.username "adrian" %}
  432. ...
  433. {% endifequal %}
  434. It is only possible to compare an argument to template variables or strings.
  435. You cannot check for equality with Python objects such as ``True`` or
  436. ``False``. If you need to test if something is true or false, use the ``if``
  437. tag instead.
  438. .. versionadded:: 1.2
  439. An alternative to the ``ifequal`` tag is to use the :ttag:`if` tag and the ``==`` operator.
  440. .. templatetag:: ifnotequal
  441. ifnotequal
  442. ~~~~~~~~~~
  443. Just like ``ifequal``, except it tests that the two arguments are not equal.
  444. .. versionadded:: 1.2
  445. An alternative to the ``ifnotequal`` tag is to use the :ttag:`if` tag and the ``!=`` operator.
  446. .. templatetag:: include
  447. include
  448. ~~~~~~~
  449. Loads a template and renders it with the current context. This is a way of
  450. "including" other templates within a template.
  451. The template name can either be a variable or a hard-coded (quoted) string,
  452. in either single or double quotes.
  453. This example includes the contents of the template ``"foo/bar.html"``::
  454. {% include "foo/bar.html" %}
  455. This example includes the contents of the template whose name is contained in
  456. the variable ``template_name``::
  457. {% include template_name %}
  458. An included template is rendered with the context of the template that's
  459. including it. This example produces the output ``"Hello, John"``:
  460. * Context: variable ``person`` is set to ``"john"``.
  461. * Template::
  462. {% include "name_snippet.html" %}
  463. * The ``name_snippet.html`` template::
  464. {{ greeting }}, {{ person|default:"friend" }}!
  465. .. versionchanged:: 1.3
  466. Additional context and exclusive context.
  467. You can pass additional context to the template using keyword arguments::
  468. {% include "name_snippet.html" with person="Jane" greeting="Hello" %}
  469. If you want to only render the context with the variables provided (or even
  470. no variables at all), use the ``only`` option::
  471. {% include "name_snippet.html" with greeting="Hi" only %}
  472. .. note::
  473. The :ttag:`include` tag should be considered as an implementation of
  474. "render this subtemplate and include the HTML", not as "parse this
  475. subtemplate and include its contents as if it were part of the parent".
  476. This means that there is no shared state between included templates --
  477. each include is a completely independent rendering process.
  478. See also: ``{% ssi %}``.
  479. .. templatetag:: load
  480. load
  481. ~~~~
  482. Load a custom template tag set.
  483. For example, the following template would load all the tags and filters
  484. registered in ``somelibrary`` and ``otherlibrary``::
  485. {% load somelibrary otherlibrary %}
  486. .. versionchanged:: 1.3
  487. You can also selectively load individual filters or tags from a library, using
  488. the ``from`` argument. In this example, the template tags/filters named ``foo``
  489. and ``bar`` will be loaded from ``somelibrary``::
  490. {% load foo bar from somelibrary %}
  491. See :doc:`Custom tag and filter libraries </howto/custom-template-tags>` for
  492. more information.
  493. .. templatetag:: now
  494. now
  495. ~~~
  496. Display the current date and/or time, using a format according to the given
  497. string. Such string can contain format specifiers characters as described
  498. in the :tfilter:`date` filter section.
  499. Example::
  500. It is {% now "jS F Y H:i" %}
  501. Note that you can backslash-escape a format string if you want to use the
  502. "raw" value. In this example, "f" is backslash-escaped, because otherwise
  503. "f" is a format string that displays the time. The "o" doesn't need to be
  504. escaped, because it's not a format character::
  505. It is the {% now "jS o\f F" %}
  506. This would display as "It is the 4th of September".
  507. .. templatetag:: regroup
  508. regroup
  509. ~~~~~~~
  510. Regroup a list of alike objects by a common attribute.
  511. This complex tag is best illustrated by use of an example: say that ``people``
  512. is a list of people represented by dictionaries with ``first_name``,
  513. ``last_name``, and ``gender`` keys:
  514. .. code-block:: python
  515. people = [
  516. {'first_name': 'George', 'last_name': 'Bush', 'gender': 'Male'},
  517. {'first_name': 'Bill', 'last_name': 'Clinton', 'gender': 'Male'},
  518. {'first_name': 'Margaret', 'last_name': 'Thatcher', 'gender': 'Female'},
  519. {'first_name': 'Condoleezza', 'last_name': 'Rice', 'gender': 'Female'},
  520. {'first_name': 'Pat', 'last_name': 'Smith', 'gender': 'Unknown'},
  521. ]
  522. ...and you'd like to display a hierarchical list that is ordered by gender,
  523. like this:
  524. * Male:
  525. * George Bush
  526. * Bill Clinton
  527. * Female:
  528. * Margaret Thatcher
  529. * Condoleezza Rice
  530. * Unknown:
  531. * Pat Smith
  532. You can use the ``{% regroup %}`` tag to group the list of people by gender.
  533. The following snippet of template code would accomplish this::
  534. {% regroup people by gender as gender_list %}
  535. <ul>
  536. {% for gender in gender_list %}
  537. <li>{{ gender.grouper }}
  538. <ul>
  539. {% for item in gender.list %}
  540. <li>{{ item.first_name }} {{ item.last_name }}</li>
  541. {% endfor %}
  542. </ul>
  543. </li>
  544. {% endfor %}
  545. </ul>
  546. Let's walk through this example. ``{% regroup %}`` takes three arguments: the
  547. list you want to regroup, the attribute to group by, and the name of the
  548. resulting list. Here, we're regrouping the ``people`` list by the ``gender``
  549. attribute and calling the result ``gender_list``.
  550. ``{% regroup %}`` produces a list (in this case, ``gender_list``) of
  551. **group objects**. Each group object has two attributes:
  552. * ``grouper`` -- the item that was grouped by (e.g., the string "Male" or
  553. "Female").
  554. * ``list`` -- a list of all items in this group (e.g., a list of all people
  555. with gender='Male').
  556. Note that ``{% regroup %}`` does not order its input! Our example relies on
  557. the fact that the ``people`` list was ordered by ``gender`` in the first place.
  558. If the ``people`` list did *not* order its members by ``gender``, the regrouping
  559. would naively display more than one group for a single gender. For example,
  560. say the ``people`` list was set to this (note that the males are not grouped
  561. together):
  562. .. code-block:: python
  563. people = [
  564. {'first_name': 'Bill', 'last_name': 'Clinton', 'gender': 'Male'},
  565. {'first_name': 'Pat', 'last_name': 'Smith', 'gender': 'Unknown'},
  566. {'first_name': 'Margaret', 'last_name': 'Thatcher', 'gender': 'Female'},
  567. {'first_name': 'George', 'last_name': 'Bush', 'gender': 'Male'},
  568. {'first_name': 'Condoleezza', 'last_name': 'Rice', 'gender': 'Female'},
  569. ]
  570. With this input for ``people``, the example ``{% regroup %}`` template code
  571. above would result in the following output:
  572. * Male:
  573. * Bill Clinton
  574. * Unknown:
  575. * Pat Smith
  576. * Female:
  577. * Margaret Thatcher
  578. * Male:
  579. * George Bush
  580. * Female:
  581. * Condoleezza Rice
  582. The easiest solution to this gotcha is to make sure in your view code that the
  583. data is ordered according to how you want to display it.
  584. Another solution is to sort the data in the template using the ``dictsort``
  585. filter, if your data is in a list of dictionaries::
  586. {% regroup people|dictsort:"gender" by gender as gender_list %}
  587. Grouping on other properties
  588. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  589. Any valid template lookup is a legal grouping attribute for the regroup
  590. tag, including methods, attributes, dictionary keys and list items. For
  591. example, if the "gender" field is a foreign key to a class with
  592. an attribute "description," you could use::
  593. {% regroup people by gender.description as gender_list %}
  594. Or, if ``gender`` is a field with ``choices``, it will have a
  595. :meth:`~django.db.models.Model.get_FOO_display` method available as an
  596. attribute, allowing you to group on the display string rather than the
  597. ``choices`` key::
  598. {% regroup people by get_gender_display as gender_list %}
  599. ``{{ gender.grouper }}`` will now display the value fields from the
  600. ``choices`` set rather than the keys.
  601. .. templatetag:: spaceless
  602. spaceless
  603. ~~~~~~~~~
  604. Removes whitespace between HTML tags. This includes tab
  605. characters and newlines.
  606. Example usage::
  607. {% spaceless %}
  608. <p>
  609. <a href="foo/">Foo</a>
  610. </p>
  611. {% endspaceless %}
  612. This example would return this HTML::
  613. <p><a href="foo/">Foo</a></p>
  614. Only space between *tags* is removed -- not space between tags and text. In
  615. this example, the space around ``Hello`` won't be stripped::
  616. {% spaceless %}
  617. <strong>
  618. Hello
  619. </strong>
  620. {% endspaceless %}
  621. .. templatetag:: ssi
  622. ssi
  623. ~~~
  624. Output the contents of a given file into the page.
  625. Like a simple "include" tag, ``{% ssi %}`` includes the contents of another
  626. file -- which must be specified using an absolute path -- in the current
  627. page::
  628. {% ssi /home/html/ljworld.com/includes/right_generic.html %}
  629. If the optional "parsed" parameter is given, the contents of the included
  630. file are evaluated as template code, within the current context::
  631. {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %}
  632. Note that if you use ``{% ssi %}``, you'll need to define
  633. :setting:`ALLOWED_INCLUDE_ROOTS` in your Django settings, as a security measure.
  634. See also: ``{% include %}``.
  635. .. admonition:: Forwards compatibility
  636. .. versionchanged:: 1.3
  637. In Django 1.5, the behavior of the :ttag:`ssi` template tag will
  638. change, with the first argument being made into a context
  639. variable, rather than being a special case unquoted constant. This
  640. will allow the :ttag:`ssi` tag to use a context variable as the
  641. value of the page to be included.
  642. In order to provide a forwards compatibility path, Django 1.3
  643. provides a future compatibility library -- ``future`` -- that
  644. implements the new behavior. To use this library, add a
  645. :ttag:`load` call at the top of any template using the :ttag:`ssi`
  646. tag, and wrap the first argument to the :ttag:`ssi` tag in quotes.
  647. For example::
  648. {% load ssi from future %}
  649. {% ssi '/home/html/ljworld.com/includes/right_generic.html' %}
  650. In Django 1.5, the unquoted constant behavior will be replaced
  651. with the behavior provided by the ``future`` tag library.
  652. Existing templates should be migrated to use the new syntax.
  653. .. templatetag:: templatetag
  654. templatetag
  655. ~~~~~~~~~~~
  656. Output one of the syntax characters used to compose template tags.
  657. Since the template system has no concept of "escaping", to display one of the
  658. bits used in template tags, you must use the ``{% templatetag %}`` tag.
  659. The argument tells which template bit to output:
  660. ================== =======
  661. Argument Outputs
  662. ================== =======
  663. ``openblock`` ``{%``
  664. ``closeblock`` ``%}``
  665. ``openvariable`` ``{{``
  666. ``closevariable`` ``}}``
  667. ``openbrace`` ``{``
  668. ``closebrace`` ``}``
  669. ``opencomment`` ``{#``
  670. ``closecomment`` ``#}``
  671. ================== =======
  672. .. templatetag:: url
  673. url
  674. ~~~
  675. Returns an absolute path reference (a URL without the domain name) matching a
  676. given view function and optional parameters. This is a way to output links
  677. without violating the DRY principle by having to hard-code URLs in your
  678. templates::
  679. {% url path.to.some_view v1 v2 %}
  680. The first argument is a path to a view function in the format
  681. ``package.package.module.function``. Additional arguments are optional and
  682. should be space-separated values that will be used as arguments in the URL.
  683. The example above shows passing positional arguments. Alternatively you may
  684. use keyword syntax::
  685. {% url path.to.some_view arg1=v1 arg2=v2 %}
  686. Do not mix both positional and keyword syntax in a single call. All arguments
  687. required by the URLconf should be present.
  688. For example, suppose you have a view, ``app_views.client``, whose URLconf
  689. takes a client ID (here, ``client()`` is a method inside the views file
  690. ``app_views.py``). The URLconf line might look like this:
  691. .. code-block:: python
  692. ('^client/(\d+)/$', 'app_views.client')
  693. If this app's URLconf is included into the project's URLconf under a path
  694. such as this:
  695. .. code-block:: python
  696. ('^clients/', include('project_name.app_name.urls'))
  697. ...then, in a template, you can create a link to this view like this::
  698. {% url app_views.client client.id %}
  699. The template tag will output the string ``/clients/client/123/``.
  700. If you're using :ref:`named URL patterns <naming-url-patterns>`, you can
  701. refer to the name of the pattern in the ``url`` tag instead of using the
  702. path to the view.
  703. Note that if the URL you're reversing doesn't exist, you'll get an
  704. :exc:`~django.core.urlresolvers.NoReverseMatch` exception raised, which will
  705. cause your site to display an error page.
  706. If you'd like to retrieve a URL without displaying it, you can use a slightly
  707. different call::
  708. {% url path.to.view arg arg2 as the_url %}
  709. <a href="{{ the_url }}">I'm linking to {{ the_url }}</a>
  710. This ``{% url ... as var %}`` syntax will *not* cause an error if the view is
  711. missing. In practice you'll use this to link to views that are optional::
  712. {% url path.to.view as the_url %}
  713. {% if the_url %}
  714. <a href="{{ the_url }}">Link to optional stuff</a>
  715. {% endif %}
  716. If you'd like to retrieve a namespaced URL, specify the fully qualified name::
  717. {% url myapp:view-name %}
  718. This will follow the normal :ref:`namespaced URL resolution strategy
  719. <topics-http-reversing-url-namespaces>`, including using any hints provided
  720. by the context as to the current application.
  721. .. versionchanged:: 1.2
  722. For backwards compatibility, the ``{% url %}`` tag also supports the
  723. use of commas to separate arguments. You shouldn't use this in any new
  724. projects, but for the sake of the people who are still using it,
  725. here's what it looks like::
  726. {% url path.to.view arg,arg2 %}
  727. {% url path.to.view arg, arg2 %}
  728. This syntax doesn't support the use of literal commas, or equals
  729. signs. Did we mention you shouldn't use this syntax in any new
  730. projects?
  731. .. admonition:: Forwards compatibility
  732. .. versionchanged:: 1.3
  733. In Django 1.5, the behavior of the :ttag:`url` template tag will
  734. change, with the first argument being made into a context
  735. variable, rather than being a special case unquoted constant. This
  736. will allow the :ttag:`url` tag to use a context variable as the
  737. value of the URL name to be reversed.
  738. In order to provide a forwards compatibility path, Django 1.3
  739. provides a future compatibility library -- ``future`` -- that
  740. implements the new behavior. To use this library, add a
  741. :ttag:`load` call at the top of any template using the :ttag:`url`
  742. tag, and wrap the first argument to the :ttag:`url` tag in quotes.
  743. For example::
  744. {% load url from future %}
  745. {% url 'myapp:view-name' %}
  746. The new library also drops support for the comma syntax for
  747. separating arguments to the :ttag:`url` template tag.
  748. In Django 1.5, the old behavior will be replaced with the behavior
  749. provided by the ``future`` tag library. Existing templates be
  750. migrated to use the new syntax.
  751. .. templatetag:: widthratio
  752. widthratio
  753. ~~~~~~~~~~
  754. For creating bar charts and such, this tag calculates the ratio of a given value
  755. to a maximum value, and then applies that ratio to a constant.
  756. For example::
  757. <img src="bar.gif" height="10" width="{% widthratio this_value max_value 100 %}" />
  758. Above, if ``this_value`` is 175 and ``max_value`` is 200, the image in the
  759. above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5
  760. which is rounded up to 88).
  761. .. templatetag:: with
  762. with
  763. ~~~~
  764. .. versionchanged:: 1.3
  765. New keyword argument format and multiple variable assignments.
  766. Caches a complex variable under a simpler name. This is useful when accessing
  767. an "expensive" method (e.g., one that hits the database) multiple times.
  768. For example::
  769. {% with total=business.employees.count %}
  770. {{ total }} employee{{ total|pluralize }}
  771. {% endwith %}
  772. The populated variable (in the example above, ``total``) is only available
  773. between the ``{% with %}`` and ``{% endwith %}`` tags.
  774. You can assign more than one context variable::
  775. {% with alpha=1 beta=2 %}
  776. ...
  777. {% endwith %}
  778. .. note:: The previous more verbose format is still supported:
  779. ``{% with business.employees.count as total %}``
  780. .. _ref-templates-builtins-filters:
  781. Built-in filter reference
  782. -------------------------
  783. .. templatefilter:: add
  784. add
  785. ~~~
  786. Adds the argument to the value.
  787. For example::
  788. {{ value|add:"2" }}
  789. If ``value`` is ``4``, then the output will be ``6``.
  790. .. versionchanged:: 1.2
  791. The following behavior didn't exist in previous Django versions.
  792. This filter will first try to coerce both values to integers. If this fails,
  793. it'll attempt to add the values together anyway. This will work on some data
  794. types (strings, list, etc.) and fail on others. If it fails, the result will
  795. be an empty string.
  796. For example, if we have::
  797. {{ first|add:second }}
  798. and ``first`` is ``[1, 2, 3]`` and ``second`` is ``[4, 5, 6]``, then the
  799. output will be ``[1, 2, 3, 4, 5, 6]``.
  800. .. warning::
  801. Strings that can be coerced to integers will be **summed**, not
  802. concatenated, as in the first example above.
  803. .. templatefilter:: addslashes
  804. addslashes
  805. ~~~~~~~~~~
  806. Adds slashes before quotes. Useful for escaping strings in CSV, for example.
  807. For example::
  808. {{ value|addslashes }}
  809. If ``value`` is ``"I'm using Django"``, the output will be ``"I\'m using Django"``.
  810. .. templatefilter:: capfirst
  811. capfirst
  812. ~~~~~~~~
  813. Capitalizes the first character of the value.
  814. For example::
  815. {{ value|capfirst }}
  816. If ``value`` is ``"django"``, the output will be ``"Django"``.
  817. .. templatefilter:: center
  818. center
  819. ~~~~~~
  820. Centers the value in a field of a given width.
  821. For example::
  822. "{{ value|center:"15" }}"
  823. If ``value`` is ``"Django"``, the output will be ``" Django "``.
  824. .. templatefilter:: cut
  825. cut
  826. ~~~
  827. Removes all values of arg from the given string.
  828. For example::
  829. {{ value|cut:" "}}
  830. If ``value`` is ``"String with spaces"``, the output will be ``"Stringwithspaces"``.
  831. .. templatefilter:: date
  832. date
  833. ~~~~
  834. Formats a date according to the given format.
  835. Uses the same format as PHP's ``date()`` function (http://php.net/date)
  836. with some custom extensions.
  837. Available format strings:
  838. ================ ======================================== =====================
  839. Format character Description Example output
  840. ================ ======================================== =====================
  841. a ``'a.m.'`` or ``'p.m.'`` (Note that ``'a.m.'``
  842. this is slightly different than PHP's
  843. output, because this includes periods
  844. to match Associated Press style.)
  845. A ``'AM'`` or ``'PM'``. ``'AM'``
  846. b Month, textual, 3 letters, lowercase. ``'jan'``
  847. B Not implemented.
  848. c ISO 8601 Format. ``2008-01-02T10:30:00.000123``
  849. d Day of the month, 2 digits with ``'01'`` to ``'31'``
  850. leading zeros.
  851. D Day of the week, textual, 3 letters. ``'Fri'``
  852. E Month, locale specific alternative
  853. representation usually used for long
  854. date representation. ``'listopada'`` (for Polish locale, as opposed to ``'Listopad'``)
  855. f Time, in 12-hour hours and minutes, ``'1'``, ``'1:30'``
  856. with minutes left off if they're zero.
  857. Proprietary extension.
  858. F Month, textual, long. ``'January'``
  859. g Hour, 12-hour format without leading ``'1'`` to ``'12'``
  860. zeros.
  861. G Hour, 24-hour format without leading ``'0'`` to ``'23'``
  862. zeros.
  863. h Hour, 12-hour format. ``'01'`` to ``'12'``
  864. H Hour, 24-hour format. ``'00'`` to ``'23'``
  865. i Minutes. ``'00'`` to ``'59'``
  866. I Not implemented.
  867. j Day of the month without leading ``'1'`` to ``'31'``
  868. zeros.
  869. l Day of the week, textual, long. ``'Friday'``
  870. L Boolean for whether it's a leap year. ``True`` or ``False``
  871. m Month, 2 digits with leading zeros. ``'01'`` to ``'12'``
  872. M Month, textual, 3 letters. ``'Jan'``
  873. n Month without leading zeros. ``'1'`` to ``'12'``
  874. N Month abbreviation in Associated Press ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'``
  875. style. Proprietary extension.
  876. O Difference to Greenwich time in hours. ``'+0200'``
  877. P Time, in 12-hour hours, minutes and ``'1 a.m.'``, ``'1:30 p.m.'``, ``'midnight'``, ``'noon'``, ``'12:30 p.m.'``
  878. 'a.m.'/'p.m.', with minutes left off
  879. if they're zero and the special-case
  880. strings 'midnight' and 'noon' if
  881. appropriate. Proprietary extension.
  882. r RFC 2822 formatted date. ``'Thu, 21 Dec 2000 16:01:07 +0200'``
  883. s Seconds, 2 digits with leading zeros. ``'00'`` to ``'59'``
  884. S English ordinal suffix for day of the ``'st'``, ``'nd'``, ``'rd'`` or ``'th'``
  885. month, 2 characters.
  886. t Number of days in the given month. ``28`` to ``31``
  887. T Time zone of this machine. ``'EST'``, ``'MDT'``
  888. u Microseconds. ``0`` to ``999999``
  889. U Seconds since the Unix Epoch
  890. (January 1 1970 00:00:00 UTC).
  891. w Day of the week, digits without ``'0'`` (Sunday) to ``'6'`` (Saturday)
  892. leading zeros.
  893. W ISO-8601 week number of year, with ``1``, ``53``
  894. weeks starting on Monday.
  895. y Year, 2 digits. ``'99'``
  896. Y Year, 4 digits. ``'1999'``
  897. z Day of the year. ``0`` to ``365``
  898. Z Time zone offset in seconds. The ``-43200`` to ``43200``
  899. offset for timezones west of UTC is
  900. always negative, and for those east of
  901. UTC is always positive.
  902. ================ ======================================== =====================
  903. .. versionadded:: 1.2
  904. The ``c`` and ``u`` format specification characters were added in Django 1.2.
  905. For example::
  906. {{ value|date:"D d M Y" }}
  907. If ``value`` is a ``datetime`` object (e.g., the result of
  908. ``datetime.datetime.now()``), the output will be the string
  909. ``'Wed 09 Jan 2008'``.
  910. The format passed can be one of the predefined ones :setting:`DATE_FORMAT`,
  911. :setting:`DATETIME_FORMAT`, :setting:`SHORT_DATE_FORMAT` or
  912. :setting:`SHORT_DATETIME_FORMAT`, or a custom format that uses the format
  913. specifiers shown in the table above. Note that predefined formats may vary
  914. depending on the current locale.
  915. Assuming that :setting:`USE_L10N` is ``True`` and :setting:`LANGUAGE_CODE` is,
  916. for example, ``"es"``, then for::
  917. {{ value|date:"SHORT_DATE_FORMAT" }}
  918. the output would be the string ``"09/01/2008"`` (the ``"SHORT_DATE_FORMAT"``
  919. format specifier for the ``es`` locale as shipped with Django is ``"d/m/Y"``).
  920. When used without a format string::
  921. {{ value|date }}
  922. ...the formatting string defined in the :setting:`DATE_FORMAT` setting will be
  923. used, without applying any localization.
  924. .. versionchanged:: 1.2
  925. Predefined formats can now be influenced by the current locale.
  926. .. templatefilter:: default
  927. default
  928. ~~~~~~~
  929. If value evaluates to ``False``, use given default. Otherwise, use the value.
  930. For example::
  931. {{ value|default:"nothing" }}
  932. If ``value`` is ``""`` (the empty string), the output will be ``nothing``.
  933. .. templatefilter:: default_if_none
  934. default_if_none
  935. ~~~~~~~~~~~~~~~
  936. If (and only if) value is ``None``, use given default. Otherwise, use the
  937. value.
  938. Note that if an empty string is given, the default value will *not* be used.
  939. Use the ``default`` filter if you want to fallback for empty strings.
  940. For example::
  941. {{ value|default_if_none:"nothing" }}
  942. If ``value`` is ``None``, the output will be the string ``"nothing"``.
  943. .. templatefilter:: dictsort
  944. dictsort
  945. ~~~~~~~~
  946. Takes a list of dictionaries and returns that list sorted by the key given in
  947. the argument.
  948. For example::
  949. {{ value|dictsort:"name" }}
  950. If ``value`` is:
  951. .. code-block:: python
  952. [
  953. {'name': 'zed', 'age': 19},
  954. {'name': 'amy', 'age': 22},
  955. {'name': 'joe', 'age': 31},
  956. ]
  957. then the output would be:
  958. .. code-block:: python
  959. [
  960. {'name': 'amy', 'age': 22},
  961. {'name': 'joe', 'age': 31},
  962. {'name': 'zed', 'age': 19},
  963. ]
  964. .. templatefilter:: dictsortreversed
  965. dictsortreversed
  966. ~~~~~~~~~~~~~~~~
  967. Takes a list of dictionaries and returns that list sorted in reverse order by
  968. the key given in the argument. This works exactly the same as the above filter,
  969. but the returned value will be in reverse order.
  970. .. templatefilter:: divisibleby
  971. divisibleby
  972. ~~~~~~~~~~~
  973. Returns ``True`` if the value is divisible by the argument.
  974. For example::
  975. {{ value|divisibleby:"3" }}
  976. If ``value`` is ``21``, the output would be ``True``.
  977. .. templatefilter:: escape
  978. escape
  979. ~~~~~~
  980. Escapes a string's HTML. Specifically, it makes these replacements:
  981. * ``<`` is converted to ``&lt;``
  982. * ``>`` is converted to ``&gt;``
  983. * ``'`` (single quote) is converted to ``&#39;``
  984. * ``"`` (double quote) is converted to ``&quot;``
  985. * ``&`` is converted to ``&amp;``
  986. The escaping is only applied when the string is output, so it does not matter
  987. where in a chained sequence of filters you put ``escape``: it will always be
  988. applied as though it were the last filter. If you want escaping to be applied
  989. immediately, use the ``force_escape`` filter.
  990. Applying ``escape`` to a variable that would normally have auto-escaping
  991. applied to the result will only result in one round of escaping being done. So
  992. it is safe to use this function even in auto-escaping environments. If you want
  993. multiple escaping passes to be applied, use the ``force_escape`` filter.
  994. .. templatefilter:: escapejs
  995. escapejs
  996. ~~~~~~~~
  997. Escapes characters for use in JavaScript strings. This does *not* make the
  998. string safe for use in HTML, but does protect you from syntax errors when using
  999. templates to generate JavaScript/JSON.
  1000. For example::
  1001. {{ value|escapejs }}
  1002. If ``value`` is ``"testing\r\njavascript \'string" <b>escaping</b>"``,
  1003. the output will be ``"testing\\u000D\\u000Ajavascript \\u0027string\\u0022 \\u003Cb\\u003Eescaping\\u003C/b\\u003E"``.
  1004. .. templatefilter:: filesizeformat
  1005. filesizeformat
  1006. ~~~~~~~~~~~~~~
  1007. Format the value like a 'human-readable' file size (i.e. ``'13 KB'``,
  1008. ``'4.1 MB'``, ``'102 bytes'``, etc).
  1009. For example::
  1010. {{ value|filesizeformat }}
  1011. If ``value`` is 123456789, the output would be ``117.7 MB``.
  1012. .. templatefilter:: first
  1013. first
  1014. ~~~~~
  1015. Returns the first item in a list.
  1016. For example::
  1017. {{ value|first }}
  1018. If ``value`` is the list ``['a', 'b', 'c']``, the output will be ``'a'``.
  1019. .. templatefilter:: fix_ampersands
  1020. fix_ampersands
  1021. ~~~~~~~~~~~~~~
  1022. .. note::
  1023. This is rarely useful as ampersands are automatically escaped. See escape_ for more information.
  1024. Replaces ampersands with ``&amp;`` entities.
  1025. For example::
  1026. {{ value|fix_ampersands }}
  1027. If ``value`` is ``Tom & Jerry``, the output will be ``Tom &amp; Jerry``.
  1028. .. templatefilter:: floatformat
  1029. floatformat
  1030. ~~~~~~~~~~~
  1031. When used without an argument, rounds a floating-point number to one decimal
  1032. place -- but only if there's a decimal part to be displayed. For example:
  1033. ============ =========================== ========
  1034. ``value`` Template Output
  1035. ============ =========================== ========
  1036. ``34.23234`` ``{{ value|floatformat }}`` ``34.2``
  1037. ``34.00000`` ``{{ value|floatformat }}`` ``34``
  1038. ``34.26000`` ``{{ value|floatformat }}`` ``34.3``
  1039. ============ =========================== ========
  1040. If used with a numeric integer argument, ``floatformat`` rounds a number to
  1041. that many decimal places. For example:
  1042. ============ ============================= ==========
  1043. ``value`` Template Output
  1044. ============ ============================= ==========
  1045. ``34.23234`` ``{{ value|floatformat:3 }}`` ``34.232``
  1046. ``34.00000`` ``{{ value|floatformat:3 }}`` ``34.000``
  1047. ``34.26000`` ``{{ value|floatformat:3 }}`` ``34.260``
  1048. ============ ============================= ==========
  1049. If the argument passed to ``floatformat`` is negative, it will round a number
  1050. to that many decimal places -- but only if there's a decimal part to be
  1051. displayed. For example:
  1052. ============ ================================ ==========
  1053. ``value`` Template Output
  1054. ============ ================================ ==========
  1055. ``34.23234`` ``{{ value|floatformat:"-3" }}`` ``34.232``
  1056. ``34.00000`` ``{{ value|floatformat:"-3" }}`` ``34``
  1057. ``34.26000`` ``{{ value|floatformat:"-3" }}`` ``34.260``
  1058. ============ ================================ ==========
  1059. Using ``floatformat`` with no argument is equivalent to using ``floatformat``
  1060. with an argument of ``-1``.
  1061. .. templatefilter:: force_escape
  1062. force_escape
  1063. ~~~~~~~~~~~~
  1064. Applies HTML escaping to a string (see the ``escape`` filter for details).
  1065. This filter is applied *immediately* and returns a new, escaped string. This
  1066. is useful in the rare cases where you need multiple escaping or want to apply
  1067. other filters to the escaped results. Normally, you want to use the ``escape``
  1068. filter.
  1069. .. templatefilter:: get_digit
  1070. get_digit
  1071. ~~~~~~~~~
  1072. Given a whole number, returns the requested digit, where 1 is the right-most
  1073. digit, 2 is the second-right-most digit, etc. Returns the original value for
  1074. invalid input (if input or argument is not an integer, or if argument is less
  1075. than 1). Otherwise, output is always an integer.
  1076. For example::
  1077. {{ value|get_digit:"2" }}
  1078. If ``value`` is ``123456789``, the output will be ``8``.
  1079. .. templatefilter:: iriencode
  1080. iriencode
  1081. ~~~~~~~~~
  1082. Converts an IRI (Internationalized Resource Identifier) to a string that is
  1083. suitable for including in a URL. This is necessary if you're trying to use
  1084. strings containing non-ASCII characters in a URL.
  1085. It's safe to use this filter on a string that has already gone through the
  1086. ``urlencode`` filter.
  1087. For example::
  1088. {{ value|iriencode }}
  1089. If ``value`` is ``"?test=1&me=2"``, the output will be ``"?test=1&amp;me=2"``.
  1090. .. templatefilter:: join
  1091. join
  1092. ~~~~
  1093. Joins a list with a string, like Python's ``str.join(list)``
  1094. For example::
  1095. {{ value|join:" // " }}
  1096. If ``value`` is the list ``['a', 'b', 'c']``, the output will be the string
  1097. ``"a // b // c"``.
  1098. .. templatefilter:: last
  1099. last
  1100. ~~~~
  1101. Returns the last item in a list.
  1102. For example::
  1103. {{ value|last }}
  1104. If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output will be the string
  1105. ``"d"``.
  1106. .. templatefilter:: length
  1107. length
  1108. ~~~~~~
  1109. Returns the length of the value. This works for both strings and lists.
  1110. For example::
  1111. {{ value|length }}
  1112. If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``4``.
  1113. .. templatefilter:: length_is
  1114. length_is
  1115. ~~~~~~~~~
  1116. Returns ``True`` if the value's length is the argument, or ``False`` otherwise.
  1117. For example::
  1118. {{ value|length_is:"4" }}
  1119. If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``True``.
  1120. .. templatefilter:: linebreaks
  1121. linebreaks
  1122. ~~~~~~~~~~
  1123. Replaces line breaks in plain text with appropriate HTML; a single
  1124. newline becomes an HTML line break (``<br />``) and a new line
  1125. followed by a blank line becomes a paragraph break (``</p>``).
  1126. For example::
  1127. {{ value|linebreaks }}
  1128. If ``value`` is ``Joel\nis a slug``, the output will be ``<p>Joel<br />is a
  1129. slug</p>``.
  1130. .. templatefilter:: linebreaksbr
  1131. linebreaksbr
  1132. ~~~~~~~~~~~~
  1133. Converts all newlines in a piece of plain text to HTML line breaks
  1134. (``<br />``).
  1135. For example::
  1136. {{ value|linebreaksbr }}
  1137. If ``value`` is ``Joel\nis a slug``, the output will be ``Joel<br />is a
  1138. slug``.
  1139. .. templatefilter:: linenumbers
  1140. linenumbers
  1141. ~~~~~~~~~~~
  1142. Displays text with line numbers.
  1143. For example::
  1144. {{ value|linenumbers }}
  1145. If ``value`` is::
  1146. one
  1147. two
  1148. three
  1149. the output will be::
  1150. 1. one
  1151. 2. two
  1152. 3. three
  1153. .. templatefilter:: ljust
  1154. ljust
  1155. ~~~~~
  1156. Left-aligns the value in a field of a given width.
  1157. **Argument:** field size
  1158. For example::
  1159. "{{ value|ljust:"10" }}"
  1160. If ``value`` is ``Django``, the output will be ``"Django "``.
  1161. .. templatefilter:: lower
  1162. lower
  1163. ~~~~~
  1164. Converts a string into all lowercase.
  1165. For example::
  1166. {{ value|lower }}
  1167. If ``value`` is ``Still MAD At Yoko``, the output will be ``still mad at yoko``.
  1168. .. templatefilter:: make_list
  1169. make_list
  1170. ~~~~~~~~~
  1171. Returns the value turned into a list. For a string, it's a list of characters.
  1172. For an integer, the argument is cast into an unicode string before creating a
  1173. list.
  1174. For example::
  1175. {{ value|make_list }}
  1176. If ``value`` is the string ``"Joel"``, the output would be the list
  1177. ``[u'J', u'o', u'e', u'l']``. If ``value`` is ``123``, the output will be the
  1178. list ``[u'1', u'2', u'3']``.
  1179. .. templatefilter:: phone2numeric
  1180. phone2numeric
  1181. ~~~~~~~~~~~~~
  1182. Converts a phone number (possibly containing letters) to its numerical
  1183. equivalent.
  1184. The input doesn't have to be a valid phone number. This will happily convert
  1185. any string.
  1186. For example::
  1187. {{ value|phone2numeric }}
  1188. If ``value`` is ``800-COLLECT``, the output will be ``800-2655328``.
  1189. .. templatefilter:: pluralize
  1190. pluralize
  1191. ~~~~~~~~~
  1192. Returns a plural suffix if the value is not 1. By default, this suffix is ``'s'``.
  1193. Example::
  1194. You have {{ num_messages }} message{{ num_messages|pluralize }}.
  1195. If ``num_messages`` is ``1``, the output will be ``You have 1 message.``
  1196. If ``num_messages`` is ``2`` the output will be ``You have 2 messages.``
  1197. For words that require a suffix other than ``'s'``, you can provide an alternate
  1198. suffix as a parameter to the filter.
  1199. Example::
  1200. You have {{ num_walruses }} walrus{{ num_walruses|pluralize:"es" }}.
  1201. For words that don't pluralize by simple suffix, you can specify both a
  1202. singular and plural suffix, separated by a comma.
  1203. Example::
  1204. You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.
  1205. .. templatefilter:: pprint
  1206. pprint
  1207. ~~~~~~
  1208. A wrapper around `pprint.pprint`__ -- for debugging, really.
  1209. __ http://docs.python.org/library/pprint.html
  1210. .. templatefilter:: random
  1211. random
  1212. ~~~~~~
  1213. Returns a random item from the given list.
  1214. For example::
  1215. {{ value|random }}
  1216. If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output could be ``"b"``.
  1217. .. templatefilter:: removetags
  1218. removetags
  1219. ~~~~~~~~~~
  1220. Removes a space-separated list of [X]HTML tags from the output.
  1221. For example::
  1222. {{ value|removetags:"b span"|safe }}
  1223. If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"`` the
  1224. output will be ``"Joel <button>is</button> a slug"``.
  1225. Note that this filter is case-sensitive.
  1226. If ``value`` is ``"<B>Joel</B> <button>is</button> a <span>slug</span>"`` the
  1227. output will be ``"<B>Joel</B> <button>is</button> a slug"``.
  1228. .. templatefilter:: rjust
  1229. rjust
  1230. ~~~~~
  1231. Right-aligns the value in a field of a given width.
  1232. **Argument:** field size
  1233. For example::
  1234. "{{ value|rjust:"10" }}"
  1235. If ``value`` is ``Django``, the output will be ``" Django"``.
  1236. .. templatefilter:: safe
  1237. safe
  1238. ~~~~
  1239. Marks a string as not requiring further HTML escaping prior to output. When
  1240. autoescaping is off, this filter has no effect.
  1241. .. note::
  1242. If you are chaining filters, a filter applied after ``safe`` can
  1243. make the contents unsafe again. For example, the following code
  1244. prints the variable as is, unescaped:
  1245. .. code-block:: html+django
  1246. {{ var|safe|escape }}
  1247. .. templatefilter:: safeseq
  1248. safeseq
  1249. ~~~~~~~
  1250. Applies the :tfilter:`safe` filter to each element of a sequence. Useful in
  1251. conjunction with other filters that operate on sequences, such as
  1252. :tfilter:`join`. For example::
  1253. {{ some_list|safeseq|join:", " }}
  1254. You couldn't use the :tfilter:`safe` filter directly in this case, as it would
  1255. first convert the variable into a string, rather than working with the
  1256. individual elements of the sequence.
  1257. .. templatefilter:: slice
  1258. slice
  1259. ~~~~~
  1260. Returns a slice of the list.
  1261. Uses the same syntax as Python's list slicing. See
  1262. http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice
  1263. for an introduction.
  1264. Example::
  1265. {{ some_list|slice:":2" }}
  1266. If ``some_list`` is ``['a', 'b', 'c']``, the output will be ``['a', 'b']``.
  1267. .. templatefilter:: slugify
  1268. slugify
  1269. ~~~~~~~
  1270. Converts to lowercase, removes non-word characters (alphanumerics and
  1271. underscores) and converts spaces to hyphens. Also strips leading and trailing
  1272. whitespace.
  1273. For example::
  1274. {{ value|slugify }}
  1275. If ``value`` is ``"Joel is a slug"``, the output will be ``"joel-is-a-slug"``.
  1276. .. templatefilter:: stringformat
  1277. stringformat
  1278. ~~~~~~~~~~~~
  1279. Formats the variable according to the argument, a string formatting specifier.
  1280. This specifier uses Python string formatting syntax, with the exception that
  1281. the leading "%" is dropped.
  1282. See http://docs.python.org/library/stdtypes.html#string-formatting-operations
  1283. for documentation of Python string formatting
  1284. For example::
  1285. {{ value|stringformat:"s" }}
  1286. If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel is a slug"``.
  1287. .. templatefilter:: striptags
  1288. striptags
  1289. ~~~~~~~~~
  1290. Strips all [X]HTML tags.
  1291. For example::
  1292. {{ value|striptags }}
  1293. If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"``, the
  1294. output will be ``"Joel is a slug"``.
  1295. .. templatefilter:: time
  1296. time
  1297. ~~~~
  1298. Formats a time according to the given format.
  1299. Given format can be the predefined one :setting:`TIME_FORMAT`, or a custom
  1300. format, same as the :tfilter:`date` filter. Note that the predefined format
  1301. is locale-dependant.
  1302. The time filter will only accept parameters in the format string that relate
  1303. to the time of day, not the date (for obvious reasons). If you need to
  1304. format a date, use the :tfilter:`date` filter.
  1305. For example::
  1306. {{ value|time:"H:i" }}
  1307. If ``value`` is equivalent to ``datetime.datetime.now()``, the output will be
  1308. the string ``"01:23"``.
  1309. Another example:
  1310. Assuming that :setting:`USE_L10N` is ``True`` and :setting:`LANGUAGE_CODE` is,
  1311. for example, ``"de"``, then for::
  1312. {{ value|time:"TIME_FORMAT" }}
  1313. the output will be the string ``"01:23:00"`` (The ``"TIME_FORMAT"`` format
  1314. specifier for the ``de`` locale as shipped with Django is ``"H:i:s"``).
  1315. When used without a format string::
  1316. {{ value|time }}
  1317. ...the formatting string defined in the :setting:`TIME_FORMAT` setting will be
  1318. used, without applying any localization.
  1319. .. versionchanged:: 1.2
  1320. Predefined formats can now be influenced by the current locale.
  1321. .. templatefilter:: timesince
  1322. timesince
  1323. ~~~~~~~~~
  1324. Formats a date as the time since that date (e.g., "4 days, 6 hours").
  1325. Takes an optional argument that is a variable containing the date to use as
  1326. the comparison point (without the argument, the comparison point is *now*).
  1327. For example, if ``blog_date`` is a date instance representing midnight on 1
  1328. June 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006,
  1329. then ``{{ blog_date|timesince:comment_date }}`` would return "8 hours".
  1330. Comparing offset-naive and offset-aware datetimes will return an empty string.
  1331. Minutes is the smallest unit used, and "0 minutes" will be returned for any
  1332. date that is in the future relative to the comparison point.
  1333. .. templatefilter:: timeuntil
  1334. timeuntil
  1335. ~~~~~~~~~
  1336. Similar to ``timesince``, except that it measures the time from now until the
  1337. given date or datetime. For example, if today is 1 June 2006 and
  1338. ``conference_date`` is a date instance holding 29 June 2006, then
  1339. ``{{ conference_date|timeuntil }}`` will return "4 weeks".
  1340. Takes an optional argument that is a variable containing the date to use as
  1341. the comparison point (instead of *now*). If ``from_date`` contains 22 June
  1342. 2006, then ``{{ conference_date|timeuntil:from_date }}`` will return "1 week".
  1343. Comparing offset-naive and offset-aware datetimes will return an empty string.
  1344. Minutes is the smallest unit used, and "0 minutes" will be returned for any
  1345. date that is in the past relative to the comparison point.
  1346. .. templatefilter:: title
  1347. title
  1348. ~~~~~
  1349. Converts a string into titlecase.
  1350. For example::
  1351. {{ value|title }}
  1352. If ``value`` is ``"my first post"``, the output will be ``"My First Post"``.
  1353. .. templatefilter:: truncatewords
  1354. truncatewords
  1355. ~~~~~~~~~~~~~
  1356. Truncates a string after a certain number of words.
  1357. **Argument:** Number of words to truncate after
  1358. For example::
  1359. {{ value|truncatewords:2 }}
  1360. If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel is ..."``.
  1361. Newlines within the string will be removed.
  1362. .. templatefilter:: truncatewords_html
  1363. truncatewords_html
  1364. ~~~~~~~~~~~~~~~~~~
  1365. Similar to ``truncatewords``, except that it is aware of HTML tags. Any tags
  1366. that are opened in the string and not closed before the truncation point, are
  1367. closed immediately after the truncation.
  1368. This is less efficient than ``truncatewords``, so should only be used when it
  1369. is being passed HTML text.
  1370. For example::
  1371. {{ value|truncatewords_html:2 }}
  1372. If ``value`` is ``"<p>Joel is a slug</p>"``, the output will be
  1373. ``"<p>Joel is ...</p>"``.
  1374. Newlines in the HTML content will be preserved.
  1375. .. templatefilter:: unordered_list
  1376. unordered_list
  1377. ~~~~~~~~~~~~~~
  1378. Recursively takes a self-nested list and returns an HTML unordered list --
  1379. WITHOUT opening and closing <ul> tags.
  1380. The list is assumed to be in the proper format. For example, if ``var`` contains
  1381. ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then
  1382. ``{{ var|unordered_list }}`` would return::
  1383. <li>States
  1384. <ul>
  1385. <li>Kansas
  1386. <ul>
  1387. <li>Lawrence</li>
  1388. <li>Topeka</li>
  1389. </ul>
  1390. </li>
  1391. <li>Illinois</li>
  1392. </ul>
  1393. </li>
  1394. Note: An older, more restrictive and verbose input format is also supported:
  1395. ``['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]``,
  1396. .. templatefilter:: upper
  1397. upper
  1398. ~~~~~
  1399. Converts a string into all uppercase.
  1400. For example::
  1401. {{ value|upper }}
  1402. If ``value`` is ``"Joel is a slug"``, the output will be ``"JOEL IS A SLUG"``.
  1403. .. templatefilter:: urlencode
  1404. urlencode
  1405. ~~~~~~~~~
  1406. Escapes a value for use in a URL.
  1407. For example::
  1408. {{ value|urlencode }}
  1409. If ``value`` is ``"http://www.example.org/foo?a=b&c=d"``, the output will be
  1410. ``"http%3A//www.example.org/foo%3Fa%3Db%26c%3Dd"``.
  1411. .. versionadded:: 1.3
  1412. An optional argument containing the characters which should not be escaped can
  1413. be provided.
  1414. If not provided, the '/' character is assumed safe. An empty string can be
  1415. provided when *all* characters should be escaped. For example::
  1416. {{ value|urlencode:"" }}
  1417. If ``value`` is ``"http://www.example.org/"``, the output will be
  1418. ``"http%3A%2F%2Fwww.example.org%2F"``.
  1419. .. templatefilter:: urlize
  1420. urlize
  1421. ~~~~~~
  1422. Converts URLs in text into clickable links.
  1423. Works on links beginning with ``http://``, ``https://``, or ``www.`` and
  1424. ending with ``.org``, ``.net`` or ``.com``. Links can have trailing punctuation
  1425. (periods, commas, close-parens) and leading punctuation (opening parens) and
  1426. ``urlize`` will still do the right thing.
  1427. Links generated by ``urlize`` have a ``rel="nofollow"`` attribute added
  1428. to them.
  1429. For example::
  1430. {{ value|urlize }}
  1431. If ``value`` is ``"Check out www.djangoproject.com"``, the output will be
  1432. ``"Check out <a href="http://www.djangoproject.com"
  1433. rel="nofollow">www.djangoproject.com</a>"``.
  1434. The ``urlize`` filter also takes an optional parameter ``autoescape``. If
  1435. ``autoescape`` is ``True``, the link text and URLs will be escaped using
  1436. Django's built-in :tfilter:`escape` filter. The default value for
  1437. ``autoescape`` is ``True``.
  1438. .. note::
  1439. If ``urlize`` is applied to text that already contains HTML markup,
  1440. things won't work as expected. Apply this filter only to plain text.
  1441. .. templatefilter:: urlizetrunc
  1442. urlizetrunc
  1443. ~~~~~~~~~~~
  1444. Converts URLs into clickable links just like urlize_, but truncates URLs
  1445. longer than the given character limit.
  1446. **Argument:** Number of characters that link text should be truncated to,
  1447. including the ellipsis that's added if truncation is necessary.
  1448. For example::
  1449. {{ value|urlizetrunc:15 }}
  1450. If ``value`` is ``"Check out www.djangoproject.com"``, the output would be
  1451. ``'Check out <a href="http://www.djangoproject.com"
  1452. rel="nofollow">www.djangopr...</a>'``.
  1453. As with urlize_, this filter should only be applied to plain text.
  1454. .. templatefilter:: wordcount
  1455. wordcount
  1456. ~~~~~~~~~
  1457. Returns the number of words.
  1458. For example::
  1459. {{ value|wordcount }}
  1460. If ``value`` is ``"Joel is a slug"``, the output will be ``4``.
  1461. .. templatefilter:: wordwrap
  1462. wordwrap
  1463. ~~~~~~~~
  1464. Wraps words at specified line length.
  1465. **Argument:** number of characters at which to wrap the text
  1466. For example::
  1467. {{ value|wordwrap:5 }}
  1468. If ``value`` is ``Joel is a slug``, the output would be::
  1469. Joel
  1470. is a
  1471. slug
  1472. .. templatefilter:: yesno
  1473. yesno
  1474. ~~~~~
  1475. Given a string mapping values for true, false and (optionally) None,
  1476. returns one of those strings according to the value:
  1477. For example::
  1478. {{ value|yesno:"yeah,no,maybe" }}
  1479. ========== ====================== ==================================
  1480. Value Argument Outputs
  1481. ========== ====================== ==================================
  1482. ``True`` ``"yeah,no,maybe"`` ``yeah``
  1483. ``False`` ``"yeah,no,maybe"`` ``no``
  1484. ``None`` ``"yeah,no,maybe"`` ``maybe``
  1485. ``None`` ``"yeah,no"`` ``"no"`` (converts None to False
  1486. if no mapping for None is given)
  1487. ========== ====================== ==================================
  1488. Other tags and filter libraries
  1489. -------------------------------
  1490. Django comes with a couple of other template-tag libraries that you have to
  1491. enable explicitly in your :setting:`INSTALLED_APPS` setting and enable in your
  1492. template with the ``{% load %}`` tag.
  1493. django.contrib.humanize
  1494. ~~~~~~~~~~~~~~~~~~~~~~~
  1495. A set of Django template filters useful for adding a "human touch" to data. See
  1496. :doc:`/ref/contrib/humanize`.
  1497. django.contrib.markup
  1498. ~~~~~~~~~~~~~~~~~~~~~
  1499. A collection of template filters that implement these common markup languages:
  1500. * Textile
  1501. * Markdown
  1502. * reST (reStructuredText)
  1503. See the :doc:`markup documentation </ref/contrib/markup>`.
  1504. django.contrib.webdesign
  1505. ~~~~~~~~~~~~~~~~~~~~~~~~
  1506. A collection of template tags that can be useful while designing a Web site,
  1507. such as a generator of Lorem Ipsum text. See :doc:`/ref/contrib/webdesign`.
  1508. i18n
  1509. ~~~~
  1510. Provides a couple of templatetags that allow specifying translatable text in
  1511. Django templates. It is slightly different from the libraries described
  1512. above because you don't need to add any application to the
  1513. :setting:`INSTALLED_APPS` setting but rather set :setting:`USE_I18N` to True,
  1514. then loading it with ``{% load i18n %}``.
  1515. See :ref:`specifying-translation-strings-in-template-code`.
  1516. l10n
  1517. ~~~~
  1518. Provides a couple of templatetags that allow control over the localization of
  1519. values in Django templates. It is slightly different from the libraries described
  1520. above because you don't need to add any application to the :setting:`INSTALLED_APPS`;
  1521. you only need to load the library using ``{% load l10n %}``.
  1522. See :ref:`topic-l10n-templates`.