builtins.txt 69 KB

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