builtins.txt 79 KB

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