builtins.txt 69 KB

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