builtins.txt 51 KB

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