2
0

builtins.txt 75 KB

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