2
0

builtins.txt 86 KB

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