builtins.txt 70 KB

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