builtins.txt 83 KB

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