builtins.txt 72 KB

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