builtins.txt 88 KB

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