builtins.txt 71 KB

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