builtins.txt 76 KB

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