builtins.txt 69 KB

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