builtins.txt 70 KB

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