builtins.txt 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089
  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 :ref:`automatic documentation
  6. <template-built-in-reference>`, 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. .. versionadded:: 1.0
  16. Control the current auto-escaping behavior. This tag takes either ``on`` or
  17. ``off`` as an argument and that determines whether auto-escaping is in effect
  18. inside the block.
  19. When auto-escaping is in effect, all variable content has HTML escaping applied
  20. to it before placing the result into the output (but after any filters have
  21. been applied). This is equivalent to manually applying the ``escape`` filter
  22. to each variable.
  23. The only exceptions are variables that are already marked as "safe" from
  24. escaping, either by the code that populated the variable, or because it has had
  25. the ``safe`` or ``escape`` filters applied.
  26. .. templatetag:: block
  27. block
  28. ~~~~~
  29. Define a block that can be overridden by child templates. See
  30. :ref:`Template inheritance <template-inheritance>` for more information.
  31. .. templatetag:: comment
  32. comment
  33. ~~~~~~~
  34. Ignore everything between ``{% comment %}`` and ``{% endcomment %}``
  35. .. templatetag:: csrf_token
  36. csrf_token
  37. ~~~~~~~~~~
  38. .. versionadded:: 1.1.2
  39. In the Django 1.1.X series, this is a no-op tag that returns an empty string for
  40. future compatibility purposes. In Django 1.2 and later, it is used for CSRF
  41. protection, as described in the documentation for :doc:`Cross Site Request
  42. Forgeries </ref/contrib/csrf>`.
  43. .. templatetag:: cycle
  44. cycle
  45. ~~~~~
  46. .. versionchanged:: 1.0
  47. Cycle among the given strings or variables each time this tag is encountered.
  48. Within a loop, cycles among the given strings each time through the
  49. loop::
  50. {% for o in some_list %}
  51. <tr class="{% cycle 'row1' 'row2' %}">
  52. ...
  53. </tr>
  54. {% endfor %}
  55. You can use variables, too. For example, if you have two template variables,
  56. ``rowvalue1`` and ``rowvalue2``, you can cycle between their values like this::
  57. {% for o in some_list %}
  58. <tr class="{% cycle rowvalue1 rowvalue2 %}">
  59. ...
  60. </tr>
  61. {% endfor %}
  62. Yes, you can mix variables and strings::
  63. {% for o in some_list %}
  64. <tr class="{% cycle 'row1' rowvalue2 'row3' %}">
  65. ...
  66. </tr>
  67. {% endfor %}
  68. In some cases you might want to refer to the next value of a cycle from
  69. outside of a loop. To do this, just give the ``{% cycle %}`` tag a name, using
  70. "as", like this::
  71. {% cycle 'row1' 'row2' as rowcolors %}
  72. From then on, you can insert the current value of the cycle wherever you'd like
  73. in your template::
  74. <tr class="{% cycle rowcolors %}">...</tr>
  75. <tr class="{% cycle rowcolors %}">...</tr>
  76. You can use any number of values in a ``{% cycle %}`` tag, separated by spaces.
  77. Values enclosed in single (``'``) or double quotes (``"``) are treated as
  78. string literals, while values without quotes are treated as template variables.
  79. Note that the variables included in the cycle will not be escaped.
  80. This is because template tags do not escape their content. Any HTML or
  81. Javascript code contained in the printed variable will be rendered
  82. as-is, which could potentially lead to security issues.
  83. If you need to escape the variables in the cycle, you must do so
  84. explicitly::
  85. {% filter force_escape %}
  86. {% cycle var1 var2 var3 %}
  87. {% endfilter %}
  88. For backwards compatibility, the ``{% cycle %}`` tag supports the much inferior
  89. old syntax from previous Django versions. You shouldn't use this in any new
  90. projects, but for the sake of the people who are still using it, here's what it
  91. looks like::
  92. {% cycle row1,row2,row3 %}
  93. In this syntax, each value gets interpreted as a literal string, and there's no
  94. way to specify variable values. Or literal commas. Or spaces. Did we mention
  95. you shouldn't use this syntax in any new projects?
  96. .. templatetag:: debug
  97. debug
  98. ~~~~~
  99. Output a whole load of debugging information, including the current context and
  100. imported modules.
  101. .. templatetag:: extends
  102. extends
  103. ~~~~~~~
  104. Signal that this template extends a parent template.
  105. This tag can be used in two ways:
  106. * ``{% extends "base.html" %}`` (with quotes) uses the literal value
  107. ``"base.html"`` as the name of the parent template to extend.
  108. * ``{% extends variable %}`` uses the value of ``variable``. If the variable
  109. evaluates to a string, Django will use that string as the name of the
  110. parent template. If the variable evaluates to a ``Template`` object,
  111. Django will use that object as the parent template.
  112. See :ref:`template-inheritance` for more information.
  113. .. templatetag:: filter
  114. filter
  115. ~~~~~~
  116. Filter the contents of the variable through variable filters.
  117. Filters can also be piped through each other, and they can have arguments --
  118. just like in variable syntax.
  119. Sample usage::
  120. {% filter force_escape|lower %}
  121. This text will be HTML-escaped, and will appear in all lowercase.
  122. {% endfilter %}
  123. .. templatetag:: firstof
  124. firstof
  125. ~~~~~~~
  126. Outputs the first variable passed that is not False, without escaping.
  127. Outputs nothing if all the passed variables are False.
  128. Sample usage::
  129. {% firstof var1 var2 var3 %}
  130. This is equivalent to::
  131. {% if var1 %}
  132. {{ var1|safe }}
  133. {% else %}{% if var2 %}
  134. {{ var2|safe }}
  135. {% else %}{% if var3 %}
  136. {{ var3|safe }}
  137. {% endif %}{% endif %}{% endif %}
  138. You can also use a literal string as a fallback value in case all
  139. passed variables are False::
  140. {% firstof var1 var2 var3 "fallback value" %}
  141. Note that the variables included in the firstof tag will not be
  142. escaped. This is because template tags do not escape their content.
  143. Any HTML or Javascript code contained in the printed variable will be
  144. rendered as-is, which could potentially lead to security issues.
  145. If you need to escape the variables in the firstof tag, you must do so
  146. explicitly::
  147. {% filter force_escape %}
  148. {% firstof var1 var2 var3 "fallback value" %}
  149. {% endfilter %}
  150. .. templatetag:: for
  151. for
  152. ~~~
  153. Loop over each item in an array. For example, to display a list of athletes
  154. provided in ``athlete_list``::
  155. <ul>
  156. {% for athlete in athlete_list %}
  157. <li>{{ athlete.name }}</li>
  158. {% endfor %}
  159. </ul>
  160. You can loop over a list in reverse by using ``{% for obj in list reversed %}``.
  161. .. versionadded:: 1.0
  162. If you need to loop over a list of lists, you can unpack the values
  163. in each sub-list into individual variables. For example, if your context
  164. contains a list of (x,y) coordinates called ``points``, you could use the
  165. following to output the list of points::
  166. {% for x, y in points %}
  167. There is a point at {{ x }},{{ y }}
  168. {% endfor %}
  169. This can also be useful if you need to access the items in a dictionary.
  170. For example, if your context contained a dictionary ``data``, the following
  171. would display the keys and values of the dictionary::
  172. {% for key, value in data.items %}
  173. {{ key }}: {{ value }}
  174. {% endfor %}
  175. The for loop sets a number of variables available within the loop:
  176. ========================== ================================================
  177. Variable Description
  178. ========================== ================================================
  179. ``forloop.counter`` The current iteration of the loop (1-indexed)
  180. ``forloop.counter0`` The current iteration of the loop (0-indexed)
  181. ``forloop.revcounter`` The number of iterations from the end of the
  182. loop (1-indexed)
  183. ``forloop.revcounter0`` The number of iterations from the end of the
  184. loop (0-indexed)
  185. ``forloop.first`` True if this is the first time through the loop
  186. ``forloop.last`` True if this is the last time through the loop
  187. ``forloop.parentloop`` For nested loops, this is the loop "above" the
  188. current one
  189. ========================== ================================================
  190. for ... empty
  191. ^^^^^^^^^^^^^
  192. .. versionadded:: 1.1
  193. The ``for`` tag can take an optional ``{% empty %}`` clause that will be
  194. displayed if the given array is empty or could not be found::
  195. <ul>
  196. {% for athlete in athlete_list %}
  197. <li>{{ athlete.name }}</li>
  198. {% empty %}
  199. <li>Sorry, no athlete in this list!</li>
  200. {% endfor %}
  201. <ul>
  202. The above is equivalent to -- but shorter, cleaner, and possibly faster
  203. than -- the following::
  204. <ul>
  205. {% if athlete_list %}
  206. {% for athlete in athlete_list %}
  207. <li>{{ athlete.name }}</li>
  208. {% endfor %}
  209. {% else %}
  210. <li>Sorry, no athletes in this list.</li>
  211. {% endif %}
  212. </ul>
  213. .. templatetag:: if
  214. if
  215. ~~
  216. The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e.
  217. exists, is not empty, and is not a false boolean value) the contents of the
  218. block are output::
  219. {% if athlete_list %}
  220. Number of athletes: {{ athlete_list|length }}
  221. {% else %}
  222. No athletes.
  223. {% endif %}
  224. In the above, if ``athlete_list`` is not empty, the number of athletes will be
  225. displayed by the ``{{ athlete_list|length }}`` variable.
  226. As you can see, the ``if`` tag can take an optional ``{% else %}`` clause that
  227. will be displayed if the test fails.
  228. Boolean operators
  229. ^^^^^^^^^^^^^^^^^
  230. ``if`` tags may use ``and``, ``or`` or ``not`` to test a number of variables or
  231. to negate a given variable::
  232. {% if athlete_list and coach_list %}
  233. Both athletes and coaches are available.
  234. {% endif %}
  235. {% if not athlete_list %}
  236. There are no athletes.
  237. {% endif %}
  238. {% if athlete_list or coach_list %}
  239. There are some athletes or some coaches.
  240. {% endif %}
  241. {% if not athlete_list or coach_list %}
  242. There are no athletes or there are some coaches (OK, so
  243. writing English translations of boolean logic sounds
  244. stupid; it's not our fault).
  245. {% endif %}
  246. {% if athlete_list and not coach_list %}
  247. There are some athletes and absolutely no coaches.
  248. {% endif %}
  249. .. versionchanged:: 1.2
  250. Use of both ``and`` and ``or`` clauses within the same tag is allowed, with
  251. ``and`` having higher precedence than ``or`` e.g.::
  252. {% if athlete_list and coach_list or cheerleader_list %}
  253. will be interpreted like:
  254. .. code-block:: python
  255. if (athlete_list and coach_list) or cheerleader_list
  256. Use of actual brackets in the ``if`` tag is invalid syntax. If you need them to
  257. indicate precedence, you should use nested ``if`` tags.
  258. .. versionadded:: 1.2
  259. ``if`` tags may also use the operators ``==``, ``!=``, ``<``, ``>``,
  260. ``<=``, ``>=`` and ``in`` which work as follows:
  261. ``==`` operator
  262. ^^^^^^^^^^^^^^^
  263. Equality. Example::
  264. {% if somevar == "x" %}
  265. This appears if variable somevar equals the string "x"
  266. {% endif %}
  267. ``!=`` operator
  268. ^^^^^^^^^^^^^^^
  269. Inequality. Example::
  270. {% if somevar != "x" %}
  271. This appears if variable somevar does not equal the string "x",
  272. or if somevar is not found in the context
  273. {% endif %}
  274. ``<`` operator
  275. ^^^^^^^^^^^^^^
  276. Less than. Example::
  277. {% if somevar < 100 %}
  278. This appears if variable somevar is less than 100.
  279. {% endif %}
  280. ``>`` operator
  281. ^^^^^^^^^^^^^^
  282. Greater than. Example::
  283. {% if somevar > 0 %}
  284. This appears if variable somevar is greater than 0.
  285. {% endif %}
  286. ``<=`` operator
  287. ^^^^^^^^^^^^^^^
  288. Less than or equal to. Example::
  289. {% if somevar <= 100 %}
  290. This appears if variable somevar is less than 100 or equal to 100.
  291. {% endif %}
  292. ``>=`` operator
  293. ^^^^^^^^^^^^^^^
  294. Greater than or equal to. Example::
  295. {% if somevar >= 1 %}
  296. This appears if variable somevar is greater than 1 or equal to 1.
  297. {% endif %}
  298. ``in`` operator
  299. ^^^^^^^^^^^^^^^
  300. Contained within. This operator is supported by many Python containers to test
  301. whether the given value is in the container. The following are some examples of
  302. how ``x in y`` will be interpreted::
  303. {% if "bc" in "abcdef" %}
  304. This appears since "bc" is a substring of "abcdef"
  305. {% endif %}
  306. {% if "hello" in greetings %}
  307. If greetings is a list or set, one element of which is the string
  308. "hello", this will appear.
  309. {% endif %}
  310. {% if user in users %}
  311. If users is a QuerySet, this will appear if user is an
  312. instance that belongs to the QuerySet.
  313. {% endif %}
  314. ``not in`` operator
  315. ~~~~~~~~~~~~~~~~~~~~
  316. Not contained within. This is the negation of the ``in`` operator.
  317. The comparison operators cannot be 'chained' like in Python or in mathematical
  318. notation. For example, instead of using::
  319. {% if a > b > c %} (WRONG)
  320. you should use::
  321. {% if a > b and b > c %}
  322. Filters
  323. ^^^^^^^
  324. You can also use filters in the ``if`` expression. For example::
  325. {% if messages|length >= 100 %}
  326. You have lots of messages today!
  327. {% endif %}
  328. Complex expressions
  329. ^^^^^^^^^^^^^^^^^^^
  330. All of the above can be combined to form complex expressions. For such
  331. expressions, it can be important to know how the operators are grouped when the
  332. expression is evaluated - that is, the precedence rules. The precedence of the
  333. operators, from lowest to highest, is as follows:
  334. * ``or``
  335. * ``and``
  336. * ``not``
  337. * ``in``
  338. * ``==``, ``!=``, ``<``, ``>``,``<=``, ``>=``
  339. (This follows Python exactly). So, for example, the following complex if tag:
  340. {% if a == b or c == d and e %}
  341. ...will be interpreted as:
  342. .. code-block:: python
  343. (a == b) or ((c == d) and e)
  344. If you need different precedence, you will need to use nested if tags. Sometimes
  345. that is better for clarity anyway, for the sake of those who do not know the
  346. precedence rules.
  347. .. templatetag:: ifchanged
  348. ifchanged
  349. ~~~~~~~~~
  350. Check if a value has changed from the last iteration of a loop.
  351. The 'ifchanged' block tag is used within a loop. It has two possible uses.
  352. 1. Checks its own rendered contents against its previous state and only
  353. displays the content if it has changed. For example, this displays a list of
  354. days, only displaying the month if it changes::
  355. <h1>Archive for {{ year }}</h1>
  356. {% for date in days %}
  357. {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
  358. <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
  359. {% endfor %}
  360. 2. If given a variable, check whether that variable has changed. For
  361. example, the following shows the date every time it changes, but
  362. only shows the hour if both the hour and the date has changed::
  363. {% for date in days %}
  364. {% ifchanged date.date %} {{ date.date }} {% endifchanged %}
  365. {% ifchanged date.hour date.date %}
  366. {{ date.hour }}
  367. {% endifchanged %}
  368. {% endfor %}
  369. The ``ifchanged`` tag can also take an optional ``{% else %}`` clause that
  370. will be displayed if the value has not changed::
  371. {% for match in matches %}
  372. <div style="background-color:
  373. {% ifchanged match.ballot_id %}
  374. {% cycle "red" "blue" %}
  375. {% else %}
  376. grey
  377. {% endifchanged %}
  378. ">{{ match }}</div>
  379. {% endfor %}
  380. .. templatetag:: ifequal
  381. ifequal
  382. ~~~~~~~
  383. Output the contents of the block if the two arguments equal each other.
  384. Example::
  385. {% ifequal user.id comment.user_id %}
  386. ...
  387. {% endifequal %}
  388. As in the ``{% if %}`` tag, an ``{% else %}`` clause is optional.
  389. The arguments can be hard-coded strings, so the following is valid::
  390. {% ifequal user.username "adrian" %}
  391. ...
  392. {% endifequal %}
  393. It is only possible to compare an argument to template variables or strings.
  394. You cannot check for equality with Python objects such as ``True`` or
  395. ``False``. If you need to test if something is true or false, use the ``if``
  396. tag instead.
  397. .. versionadded:: 1.2
  398. An alternative to the ``ifequal`` tag is to use the :ttag:`if` tag and the ``==`` operator.
  399. .. templatetag:: ifnotequal
  400. ifnotequal
  401. ~~~~~~~~~~
  402. Just like ``ifequal``, except it tests that the two arguments are not equal.
  403. .. versionadded:: 1.2
  404. An alternative to the ``ifnotequal`` tag is to use the :ttag:`if` tag and the ``!=`` operator.
  405. .. templatetag:: include
  406. include
  407. ~~~~~~~
  408. Loads a template and renders it with the current context. This is a way of
  409. "including" other templates within a template.
  410. The template name can either be a variable or a hard-coded (quoted) string,
  411. in either single or double quotes.
  412. This example includes the contents of the template ``"foo/bar.html"``::
  413. {% include "foo/bar.html" %}
  414. This example includes the contents of the template whose name is contained in
  415. the variable ``template_name``::
  416. {% include template_name %}
  417. An included template is rendered with the context of the template that's
  418. including it. This example produces the output ``"Hello, John"``:
  419. * Context: variable ``person`` is set to ``"john"``.
  420. * Template::
  421. {% include "name_snippet.html" %}
  422. * The ``name_snippet.html`` template::
  423. Hello, {{ person }}
  424. See also: ``{% ssi %}``.
  425. .. note::
  426. The :ttag:`include` tag should be considered as an implementation of
  427. "render this subtemplate and include the HTML", not as "parse this
  428. subtemplate and include its contents as if it were part of the parent".
  429. This means that there is no shared state between included templates --
  430. each include is a completely independent rendering process.
  431. .. templatetag:: load
  432. load
  433. ~~~~
  434. Load a custom template tag set.
  435. See :doc:`Custom tag and filter libraries </howto/custom-template-tags>` for more information.
  436. .. templatetag:: now
  437. now
  438. ~~~
  439. Display the date, formatted according to the given string.
  440. Uses the same format as PHP's ``date()`` function (http://php.net/date)
  441. with some custom extensions.
  442. Available format strings:
  443. ================ ======================================== =====================
  444. Format character Description Example output
  445. ================ ======================================== =====================
  446. a ``'a.m.'`` or ``'p.m.'`` (Note that ``'a.m.'``
  447. this is slightly different than PHP's
  448. output, because this includes periods
  449. to match Associated Press style.)
  450. A ``'AM'`` or ``'PM'``. ``'AM'``
  451. b Month, textual, 3 letters, lowercase. ``'jan'``
  452. B Not implemented.
  453. c ISO 8601 Format. ``2008-01-02T10:30:00.000123``
  454. d Day of the month, 2 digits with ``'01'`` to ``'31'``
  455. leading zeros.
  456. D Day of the week, textual, 3 letters. ``'Fri'``
  457. f Time, in 12-hour hours and minutes, ``'1'``, ``'1:30'``
  458. with minutes left off if they're zero.
  459. Proprietary extension.
  460. F Month, textual, long. ``'January'``
  461. g Hour, 12-hour format without leading ``'1'`` to ``'12'``
  462. zeros.
  463. G Hour, 24-hour format without leading ``'0'`` to ``'23'``
  464. zeros.
  465. h Hour, 12-hour format. ``'01'`` to ``'12'``
  466. H Hour, 24-hour format. ``'00'`` to ``'23'``
  467. i Minutes. ``'00'`` to ``'59'``
  468. I Not implemented.
  469. j Day of the month without leading ``'1'`` to ``'31'``
  470. zeros.
  471. l Day of the week, textual, long. ``'Friday'``
  472. L Boolean for whether it's a leap year. ``True`` or ``False``
  473. m Month, 2 digits with leading zeros. ``'01'`` to ``'12'``
  474. M Month, textual, 3 letters. ``'Jan'``
  475. n Month without leading zeros. ``'1'`` to ``'12'``
  476. N Month abbreviation in Associated Press ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'``
  477. style. Proprietary extension.
  478. O Difference to Greenwich time in hours. ``'+0200'``
  479. P Time, in 12-hour hours, minutes and ``'1 a.m.'``, ``'1:30 p.m.'``, ``'midnight'``, ``'noon'``, ``'12:30 p.m.'``
  480. 'a.m.'/'p.m.', with minutes left off
  481. if they're zero and the special-case
  482. strings 'midnight' and 'noon' if
  483. appropriate. Proprietary extension.
  484. r RFC 2822 formatted date. ``'Thu, 21 Dec 2000 16:01:07 +0200'``
  485. s Seconds, 2 digits with leading zeros. ``'00'`` to ``'59'``
  486. S English ordinal suffix for day of the ``'st'``, ``'nd'``, ``'rd'`` or ``'th'``
  487. month, 2 characters.
  488. t Number of days in the given month. ``28`` to ``31``
  489. T Time zone of this machine. ``'EST'``, ``'MDT'``
  490. u Microseconds. ``0`` to ``999999``
  491. U Seconds since the Unix Epoch
  492. (January 1 1970 00:00:00 UTC).
  493. w Day of the week, digits without ``'0'`` (Sunday) to ``'6'`` (Saturday)
  494. leading zeros.
  495. W ISO-8601 week number of year, with ``1``, ``53``
  496. weeks starting on Monday.
  497. y Year, 2 digits. ``'99'``
  498. Y Year, 4 digits. ``'1999'``
  499. z Day of the year. ``0`` to ``365``
  500. Z Time zone offset in seconds. The ``-43200`` to ``43200``
  501. offset for timezones west of UTC is
  502. always negative, and for those east of
  503. UTC is always positive.
  504. ================ ======================================== =====================
  505. Example::
  506. It is {% now "jS F Y H:i" %}
  507. Note that you can backslash-escape a format string if you want to use the
  508. "raw" value. In this example, "f" is backslash-escaped, because otherwise
  509. "f" is a format string that displays the time. The "o" doesn't need to be
  510. escaped, because it's not a format character::
  511. It is the {% now "jS o\f F" %}
  512. This would display as "It is the 4th of September".
  513. .. versionadded:: 1.2
  514. The ``c`` and ``u`` format specification characters were added in Django 1.2.
  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. .. templatetag:: spaceless
  596. spaceless
  597. ~~~~~~~~~
  598. Removes whitespace between HTML tags. This includes tab
  599. characters and newlines.
  600. Example usage::
  601. {% spaceless %}
  602. <p>
  603. <a href="foo/">Foo</a>
  604. </p>
  605. {% endspaceless %}
  606. This example would return this HTML::
  607. <p><a href="foo/">Foo</a></p>
  608. Only space between *tags* is removed -- not space between tags and text. In
  609. this example, the space around ``Hello`` won't be stripped::
  610. {% spaceless %}
  611. <strong>
  612. Hello
  613. </strong>
  614. {% endspaceless %}
  615. .. templatetag:: ssi
  616. ssi
  617. ~~~
  618. Output the contents of a given file into the page.
  619. Like a simple "include" tag, ``{% ssi %}`` includes the contents of another
  620. file -- which must be specified using an absolute path -- in the current
  621. page::
  622. {% ssi /home/html/ljworld.com/includes/right_generic.html %}
  623. If the optional "parsed" parameter is given, the contents of the included
  624. file are evaluated as template code, within the current context::
  625. {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %}
  626. Note that if you use ``{% ssi %}``, you'll need to define
  627. :setting:`ALLOWED_INCLUDE_ROOTS` in your Django settings, as a security measure.
  628. See also: ``{% include %}``.
  629. .. templatetag:: templatetag
  630. templatetag
  631. ~~~~~~~~~~~
  632. Output one of the syntax characters used to compose template tags.
  633. Since the template system has no concept of "escaping", to display one of the
  634. bits used in template tags, you must use the ``{% templatetag %}`` tag.
  635. The argument tells which template bit to output:
  636. ================== =======
  637. Argument Outputs
  638. ================== =======
  639. ``openblock`` ``{%``
  640. ``closeblock`` ``%}``
  641. ``openvariable`` ``{{``
  642. ``closevariable`` ``}}``
  643. ``openbrace`` ``{``
  644. ``closebrace`` ``}``
  645. ``opencomment`` ``{#``
  646. ``closecomment`` ``#}``
  647. ================== =======
  648. .. templatetag:: url
  649. url
  650. ~~~
  651. Returns an absolute URL (i.e., a URL without the domain name) matching a given
  652. view function and optional parameters. This is a way to output links without
  653. violating the DRY principle by having to hard-code URLs in your templates::
  654. {% url path.to.some_view v1 v2 %}
  655. The first argument is a path to a view function in the format
  656. ``package.package.module.function``. Additional arguments are optional and
  657. should be space-separated values that will be used as arguments in the URL.
  658. The example above shows passing positional arguments. Alternatively you may
  659. use keyword syntax::
  660. {% url path.to.some_view arg1=v1 arg2=v2 %}
  661. Do not mix both positional and keyword syntax in a single call. All arguments
  662. required by the URLconf should be present.
  663. For example, suppose you have a view, ``app_views.client``, whose URLconf
  664. takes a client ID (here, ``client()`` is a method inside the views file
  665. ``app_views.py``). The URLconf line might look like this:
  666. .. code-block:: python
  667. ('^client/(\d+)/$', 'app_views.client')
  668. If this app's URLconf is included into the project's URLconf under a path
  669. such as this:
  670. .. code-block:: python
  671. ('^clients/', include('project_name.app_name.urls'))
  672. ...then, in a template, you can create a link to this view like this::
  673. {% url app_views.client client.id %}
  674. The template tag will output the string ``/clients/client/123/``.
  675. .. versionadded:: 1.0
  676. If you're using :ref:`named URL patterns <naming-url-patterns>`, you can
  677. refer to the name of the pattern in the ``url`` tag instead of using the
  678. path to the view.
  679. Note that if the URL you're reversing doesn't exist, you'll get an
  680. :exc:`NoReverseMatch` exception raised, which will cause your site to display an
  681. error page.
  682. .. versionadded:: 1.0
  683. If you'd like to retrieve a URL without displaying it, you can use a slightly
  684. different call::
  685. {% url path.to.view arg arg2 as the_url %}
  686. <a href="{{ the_url }}">I'm linking to {{ the_url }}</a>
  687. This ``{% url ... as var %}`` syntax will *not* cause an error if the view is
  688. missing. In practice you'll use this to link to views that are optional::
  689. {% url path.to.view as the_url %}
  690. {% if the_url %}
  691. <a href="{{ the_url }}">Link to optional stuff</a>
  692. {% endif %}
  693. .. versionadded:: 1.1
  694. If you'd like to retrieve a namespaced URL, specify the fully qualified name::
  695. {% url myapp:view-name %}
  696. This will follow the normal :ref:`namespaced URL resolution strategy
  697. <topics-http-reversing-url-namespaces>`, including using any hints provided
  698. by the context as to the current application.
  699. .. versionchanged:: 1.2
  700. For backwards compatibility, the ``{% url %}`` tag also supports the
  701. use of commas to separate arguments. You shouldn't use this in any new
  702. projects, but for the sake of the people who are still using it,
  703. here's what it looks like::
  704. {% url path.to.view arg,arg2 %}
  705. {% url path.to.view arg, arg2 %}
  706. This syntax doesn't support the use of literal commas, or or equals
  707. signs. Did we mention you shouldn't use this syntax in any new
  708. projects?
  709. .. templatetag:: widthratio
  710. widthratio
  711. ~~~~~~~~~~
  712. For creating bar charts and such, this tag calculates the ratio of a given value
  713. to a maximum value, and then applies that ratio to a constant.
  714. For example::
  715. <img src="bar.gif" height="10" width="{% widthratio this_value max_value 100 %}" />
  716. Above, if ``this_value`` is 175 and ``max_value`` is 200, the image in the
  717. above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5
  718. which is rounded up to 88).
  719. .. templatetag:: with
  720. with
  721. ~~~~
  722. .. versionadded:: 1.0
  723. Caches a complex variable under a simpler name. This is useful when accessing
  724. an "expensive" method (e.g., one that hits the database) multiple times.
  725. For example::
  726. {% with business.employees.count as total %}
  727. {{ total }} employee{{ total|pluralize }}
  728. {% endwith %}
  729. The populated variable (in the example above, ``total``) is only available
  730. between the ``{% with %}`` and ``{% endwith %}`` tags.
  731. .. _ref-templates-builtins-filters:
  732. Built-in filter reference
  733. -------------------------
  734. .. templatefilter:: add
  735. add
  736. ~~~
  737. Adds the argument to the value.
  738. For example::
  739. {{ value|add:"2" }}
  740. If ``value`` is ``4``, then the output will be ``6``.
  741. .. versionchanged:: 1.2
  742. The following behavior didn't exist in previous Django versions.
  743. This filter will first try to coerce both values to integers. If this fails,
  744. it'll attempt to add the values together anyway. This will work on some data
  745. types (strings, list, etc.) and fail on others. If it fails, the result will
  746. be an empty string.
  747. For example, if we have::
  748. {{ first|add:second }}
  749. and ``first`` is ``[1, 2, 3]`` and ``second`` is ``[4, 5, 6]``, then the
  750. output will be ``[1, 2, 3, 4, 5, 6]``.
  751. .. warning::
  752. Keep in mind that strings that can both be coerced to integers will be,
  753. and thus will be will be *summed*, not concatenated, as in the first
  754. example above.
  755. .. templatefilter:: addslashes
  756. addslashes
  757. ~~~~~~~~~~
  758. Adds slashes before quotes. Useful for escaping strings in CSV, for example.
  759. For example::
  760. {{ value|addslashes }}
  761. If ``value`` is ``"I'm using Django"``, the output will be ``"I\'m using Django"``.
  762. .. templatefilter:: capfirst
  763. capfirst
  764. ~~~~~~~~
  765. Capitalizes the first character of the value.
  766. For example::
  767. {{ value|capfirst }}
  768. If ``value`` is ``"django"``, the output will be ``"Django"``.
  769. .. templatefilter:: center
  770. center
  771. ~~~~~~
  772. Centers the value in a field of a given width.
  773. For example::
  774. "{{ value|center:"15" }}"
  775. If ``value`` is ``"Django"``, the output will be ``" Django "``.
  776. .. templatefilter:: cut
  777. cut
  778. ~~~
  779. Removes all values of arg from the given string.
  780. For example::
  781. {{ value|cut:" "}}
  782. If ``value`` is ``"String with spaces"``, the output will be ``"Stringwithspaces"``.
  783. .. templatefilter:: date
  784. date
  785. ~~~~
  786. Formats a date according to the given format.
  787. Given format can be one of the predefined ones ``DATE_FORMAT``,
  788. ``DATETIME_FORMAT``, ``SHORT_DATE_FORMAT`` or ``SHORT_DATETIME_FORMAT``,
  789. or a custom format, same as the :ttag:`now` tag. Note that predefined formats
  790. may vary depending on the current locale.
  791. For example::
  792. {{ value|date:"D d M Y" }}
  793. If ``value`` is a ``datetime`` object (e.g., the result of
  794. ``datetime.datetime.now()``), the output will be the string
  795. ``'Wed 09 Jan 2008'``.
  796. Another example:
  797. Assuming that :setting:`USE_L10N` is ``True`` and :setting:`LANGUAGE_CODE` is,
  798. for example, ``"es"``, then for::
  799. {{ value|date:"SHORT_DATE_FORMAT" }}
  800. the output will be the string ``"09/01/2008"`` (The ``"SHORT_DATE_FORMAT"``
  801. format specifier for the ``es`` locale as shipped with Django is ``"d/m/Y"``).
  802. When used without a format string::
  803. {{ value|date }}
  804. ...the formatting string defined in the :setting:`DATE_FORMAT` setting will be
  805. used, without applying any localization.
  806. .. versionchanged:: 1.2
  807. Predefined formats can now be influenced by the current locale.
  808. .. templatefilter:: default
  809. default
  810. ~~~~~~~
  811. If value evaluates to ``False``, use given default. Otherwise, use the value.
  812. For example::
  813. {{ value|default:"nothing" }}
  814. If ``value`` is ``""`` (the empty string), the output will be ``nothing``.
  815. .. templatefilter:: default_if_none
  816. default_if_none
  817. ~~~~~~~~~~~~~~~
  818. If (and only if) value is ``None``, use given default. Otherwise, use the
  819. value.
  820. Note that if an empty string is given, the default value will *not* be used.
  821. Use the ``default`` filter if you want to fallback for empty strings.
  822. For example::
  823. {{ value|default_if_none:"nothing" }}
  824. If ``value`` is ``None``, the output will be the string ``"nothing"``.
  825. .. templatefilter:: dictsort
  826. dictsort
  827. ~~~~~~~~
  828. Takes a list of dictionaries and returns that list sorted by the key given in
  829. the argument.
  830. For example::
  831. {{ value|dictsort:"name" }}
  832. If ``value`` is:
  833. .. code-block:: python
  834. [
  835. {'name': 'zed', 'age': 19},
  836. {'name': 'amy', 'age': 22},
  837. {'name': 'joe', 'age': 31},
  838. ]
  839. then the output would be:
  840. .. code-block:: python
  841. [
  842. {'name': 'amy', 'age': 22},
  843. {'name': 'joe', 'age': 31},
  844. {'name': 'zed', 'age': 19},
  845. ]
  846. .. templatefilter:: dictsortreversed
  847. dictsortreversed
  848. ~~~~~~~~~~~~~~~~
  849. Takes a list of dictionaries and returns that list sorted in reverse order by
  850. the key given in the argument. This works exactly the same as the above filter,
  851. but the returned value will be in reverse order.
  852. .. templatefilter:: divisibleby
  853. divisibleby
  854. ~~~~~~~~~~~
  855. Returns ``True`` if the value is divisible by the argument.
  856. For example::
  857. {{ value|divisibleby:"3" }}
  858. If ``value`` is ``21``, the output would be ``True``.
  859. .. templatefilter:: escape
  860. escape
  861. ~~~~~~
  862. Escapes a string's HTML. Specifically, it makes these replacements:
  863. * ``<`` is converted to ``&lt;``
  864. * ``>`` is converted to ``&gt;``
  865. * ``'`` (single quote) is converted to ``&#39;``
  866. * ``"`` (double quote) is converted to ``&quot;``
  867. * ``&`` is converted to ``&amp;``
  868. The escaping is only applied when the string is output, so it does not matter
  869. where in a chained sequence of filters you put ``escape``: it will always be
  870. applied as though it were the last filter. If you want escaping to be applied
  871. immediately, use the ``force_escape`` filter.
  872. Applying ``escape`` to a variable that would normally have auto-escaping
  873. applied to the result will only result in one round of escaping being done. So
  874. it is safe to use this function even in auto-escaping environments. If you want
  875. multiple escaping passes to be applied, use the ``force_escape`` filter.
  876. .. versionchanged:: 1.0
  877. Due to auto-escaping, the behavior of this filter has changed slightly.
  878. The replacements are only made once, after
  879. all other filters are applied -- including filters before and after it.
  880. .. templatefilter:: escapejs
  881. escapejs
  882. ~~~~~~~~
  883. .. versionadded:: 1.0
  884. Escapes characters for use in JavaScript strings. This does *not* make the
  885. string safe for use in HTML, but does protect you from syntax errors when using
  886. templates to generate JavaScript/JSON.
  887. For example::
  888. {{ value|escapejs }}
  889. If ``value`` is ``"testing\r\njavascript \'string" <b>escaping</b>"``,
  890. the output will be ``"testing\\u000D\\u000Ajavascript \\u0027string\\u0022 \\u003Cb\\u003Eescaping\\u003C/b\\u003E"``.
  891. .. templatefilter:: filesizeformat
  892. filesizeformat
  893. ~~~~~~~~~~~~~~
  894. Format the value like a 'human-readable' file size (i.e. ``'13 KB'``,
  895. ``'4.1 MB'``, ``'102 bytes'``, etc).
  896. For example::
  897. {{ value|filesizeformat }}
  898. If ``value`` is 123456789, the output would be ``117.7 MB``.
  899. .. templatefilter:: first
  900. first
  901. ~~~~~
  902. Returns the first item in a list.
  903. For example::
  904. {{ value|first }}
  905. If ``value`` is the list ``['a', 'b', 'c']``, the output will be ``'a'``.
  906. .. templatefilter:: fix_ampersands
  907. fix_ampersands
  908. ~~~~~~~~~~~~~~
  909. .. versionchanged:: 1.0
  910. This is rarely useful as ampersands are now automatically escaped. See escape_ for more information.
  911. Replaces ampersands with ``&amp;`` entities.
  912. For example::
  913. {{ value|fix_ampersands }}
  914. If ``value`` is ``Tom & Jerry``, the output will be ``Tom &amp; Jerry``.
  915. .. templatefilter:: floatformat
  916. floatformat
  917. ~~~~~~~~~~~
  918. When used without an argument, rounds a floating-point number to one decimal
  919. place -- but only if there's a decimal part to be displayed. For example:
  920. ============ =========================== ========
  921. ``value`` Template Output
  922. ============ =========================== ========
  923. ``34.23234`` ``{{ value|floatformat }}`` ``34.2``
  924. ``34.00000`` ``{{ value|floatformat }}`` ``34``
  925. ``34.26000`` ``{{ value|floatformat }}`` ``34.3``
  926. ============ =========================== ========
  927. If used with a numeric integer argument, ``floatformat`` rounds a number to
  928. that many decimal places. For example:
  929. ============ ============================= ==========
  930. ``value`` Template Output
  931. ============ ============================= ==========
  932. ``34.23234`` ``{{ value|floatformat:3 }}`` ``34.232``
  933. ``34.00000`` ``{{ value|floatformat:3 }}`` ``34.000``
  934. ``34.26000`` ``{{ value|floatformat:3 }}`` ``34.260``
  935. ============ ============================= ==========
  936. If the argument passed to ``floatformat`` is negative, it will round a number
  937. to that many decimal places -- but only if there's a decimal part to be
  938. displayed. For example:
  939. ============ ================================ ==========
  940. ``value`` Template Output
  941. ============ ================================ ==========
  942. ``34.23234`` ``{{ value|floatformat:"-3" }}`` ``34.232``
  943. ``34.00000`` ``{{ value|floatformat:"-3" }}`` ``34``
  944. ``34.26000`` ``{{ value|floatformat:"-3" }}`` ``34.260``
  945. ============ ================================ ==========
  946. Using ``floatformat`` with no argument is equivalent to using ``floatformat``
  947. with an argument of ``-1``.
  948. .. templatefilter:: force_escape
  949. force_escape
  950. ~~~~~~~~~~~~
  951. .. versionadded:: 1.0
  952. Applies HTML escaping to a string (see the ``escape`` filter for details).
  953. This filter is applied *immediately* and returns a new, escaped string. This
  954. is useful in the rare cases where you need multiple escaping or want to apply
  955. other filters to the escaped results. Normally, you want to use the ``escape``
  956. filter.
  957. .. templatefilter:: get_digit
  958. get_digit
  959. ~~~~~~~~~
  960. Given a whole number, returns the requested digit, where 1 is the right-most
  961. digit, 2 is the second-right-most digit, etc. Returns the original value for
  962. invalid input (if input or argument is not an integer, or if argument is less
  963. than 1). Otherwise, output is always an integer.
  964. For example::
  965. {{ value|get_digit:"2" }}
  966. If ``value`` is ``123456789``, the output will be ``8``.
  967. .. templatefilter:: iriencode
  968. iriencode
  969. ~~~~~~~~~
  970. Converts an IRI (Internationalized Resource Identifier) to a string that is
  971. suitable for including in a URL. This is necessary if you're trying to use
  972. strings containing non-ASCII characters in a URL.
  973. It's safe to use this filter on a string that has already gone through the
  974. ``urlencode`` filter.
  975. For example::
  976. {{ value|iriencode }}
  977. If ``value`` is ``"?test=1&me=2"``, the output will be ``"?test=1&amp;me=2"``.
  978. .. templatefilter:: join
  979. join
  980. ~~~~
  981. Joins a list with a string, like Python's ``str.join(list)``
  982. For example::
  983. {{ value|join:" // " }}
  984. If ``value`` is the list ``['a', 'b', 'c']``, the output will be the string
  985. ``"a // b // c"``.
  986. .. templatefilter:: last
  987. last
  988. ~~~~
  989. .. versionadded:: 1.0
  990. Returns the last item in a list.
  991. For example::
  992. {{ value|last }}
  993. If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output will be the string
  994. ``"d"``.
  995. .. templatefilter:: length
  996. length
  997. ~~~~~~
  998. Returns the length of the value. This works for both strings and lists.
  999. For example::
  1000. {{ value|length }}
  1001. If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``4``.
  1002. .. templatefilter:: length_is
  1003. length_is
  1004. ~~~~~~~~~
  1005. Returns ``True`` if the value's length is the argument, or ``False`` otherwise.
  1006. For example::
  1007. {{ value|length_is:"4" }}
  1008. If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``True``.
  1009. .. templatefilter:: linebreaks
  1010. linebreaks
  1011. ~~~~~~~~~~
  1012. Replaces line breaks in plain text with appropriate HTML; a single
  1013. newline becomes an HTML line break (``<br />``) and a new line
  1014. followed by a blank line becomes a paragraph break (``</p>``).
  1015. For example::
  1016. {{ value|linebreaks }}
  1017. If ``value`` is ``Joel\nis a slug``, the output will be ``<p>Joel<br />is a
  1018. slug</p>``.
  1019. .. templatefilter:: linebreaksbr
  1020. linebreaksbr
  1021. ~~~~~~~~~~~~
  1022. Converts all newlines in a piece of plain text to HTML line breaks
  1023. (``<br />``).
  1024. For example::
  1025. {{ value|linebreaksbr }}
  1026. If ``value`` is ``Joel\nis a slug``, the output will be ``Joel<br />is a
  1027. slug``.
  1028. .. templatefilter:: linenumbers
  1029. linenumbers
  1030. ~~~~~~~~~~~
  1031. Displays text with line numbers.
  1032. For example::
  1033. {{ value|linenumbers }}
  1034. If ``value`` is::
  1035. one
  1036. two
  1037. three
  1038. the output will be::
  1039. 1. one
  1040. 2. two
  1041. 3. three
  1042. .. templatefilter:: ljust
  1043. ljust
  1044. ~~~~~
  1045. Left-aligns the value in a field of a given width.
  1046. **Argument:** field size
  1047. For example::
  1048. "{{ value|ljust:"10" }}"
  1049. If ``value`` is ``Django``, the output will be ``"Django "``.
  1050. .. templatefilter:: lower
  1051. lower
  1052. ~~~~~
  1053. Converts a string into all lowercase.
  1054. For example::
  1055. {{ value|lower }}
  1056. If ``value`` is ``Still MAD At Yoko``, the output will be ``still mad at yoko``.
  1057. .. templatefilter:: make_list
  1058. make_list
  1059. ~~~~~~~~~
  1060. Returns the value turned into a list. For an integer, it's a list of
  1061. digits. For a string, it's a list of characters.
  1062. For example::
  1063. {{ value|make_list }}
  1064. If ``value`` is the string ``"Joel"``, the output would be the list
  1065. ``[u'J', u'o', u'e', u'l']``. If ``value`` is ``123``, the output will be the
  1066. list ``[1, 2, 3]``.
  1067. .. templatefilter:: phone2numeric
  1068. phone2numeric
  1069. ~~~~~~~~~~~~~
  1070. Converts a phone number (possibly containing letters) to its numerical
  1071. equivalent.
  1072. The input doesn't have to be a valid phone number. This will happily convert
  1073. any string.
  1074. For example::
  1075. {{ value|phone2numeric }}
  1076. If ``value`` is ``800-COLLECT``, the output will be ``800-2655328``.
  1077. .. templatefilter:: pluralize
  1078. pluralize
  1079. ~~~~~~~~~
  1080. Returns a plural suffix if the value is not 1. By default, this suffix is ``'s'``.
  1081. Example::
  1082. You have {{ num_messages }} message{{ num_messages|pluralize }}.
  1083. If ``num_messages`` is ``1``, the output will be ``You have 1 message.``
  1084. If ``num_messages`` is ``2`` the output will be ``You have 2 messages.``
  1085. For words that require a suffix other than ``'s'``, you can provide an alternate
  1086. suffix as a parameter to the filter.
  1087. Example::
  1088. You have {{ num_walruses }} walrus{{ num_walruses|pluralize:"es" }}.
  1089. For words that don't pluralize by simple suffix, you can specify both a
  1090. singular and plural suffix, separated by a comma.
  1091. Example::
  1092. You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.
  1093. .. templatefilter:: pprint
  1094. pprint
  1095. ~~~~~~
  1096. A wrapper around `pprint.pprint`__ -- for debugging, really.
  1097. __ http://docs.python.org/library/pprint.html
  1098. .. templatefilter:: random
  1099. random
  1100. ~~~~~~
  1101. Returns a random item from the given list.
  1102. For example::
  1103. {{ value|random }}
  1104. If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output could be ``"b"``.
  1105. .. templatefilter:: removetags
  1106. removetags
  1107. ~~~~~~~~~~
  1108. Removes a space-separated list of [X]HTML tags from the output.
  1109. For example::
  1110. {{ value|removetags:"b span"|safe }}
  1111. If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"`` the
  1112. output will be ``"Joel <button>is</button> a slug"``.
  1113. .. templatefilter:: rjust
  1114. rjust
  1115. ~~~~~
  1116. Right-aligns the value in a field of a given width.
  1117. **Argument:** field size
  1118. For example::
  1119. "{{ value|rjust:"10" }}"
  1120. If ``value`` is ``Django``, the output will be ``" Django"``.
  1121. .. templatefilter:: safe
  1122. safe
  1123. ~~~~
  1124. Marks a string as not requiring further HTML escaping prior to output. When
  1125. autoescaping is off, this filter has no effect.
  1126. .. note::
  1127. If you are chaining filters, a filter applied after ``safe`` can
  1128. make the contents unsafe again. For example, the following code
  1129. prints the variable as is, unescaped:
  1130. .. code-block:: html+django
  1131. {{ var|safe|escape }}
  1132. .. templatefilter:: safeseq
  1133. safeseq
  1134. ~~~~~~~
  1135. Applies the :tfilter:`safe` filter to each element of a sequence. Useful in
  1136. conjunction with other filters that operate on sequences, such as
  1137. :tfilter:`join`. For example::
  1138. {{ some_list|safeseq|join:", " }}
  1139. You couldn't use the :tfilter:`safe` filter directly in this case, as it would
  1140. first convert the variable into a string, rather than working with the
  1141. individual elements of the sequence.
  1142. .. templatefilter:: slice
  1143. slice
  1144. ~~~~~
  1145. Returns a slice of the list.
  1146. Uses the same syntax as Python's list slicing. See
  1147. http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice
  1148. for an introduction.
  1149. Example::
  1150. {{ some_list|slice:":2" }}
  1151. If ``some_list`` is ``['a', 'b', 'c']``, the output will be ``['a', 'b']``.
  1152. .. templatefilter:: slugify
  1153. slugify
  1154. ~~~~~~~
  1155. Converts to lowercase, removes non-word characters (alphanumerics and
  1156. underscores) and converts spaces to hyphens. Also strips leading and trailing
  1157. whitespace.
  1158. For example::
  1159. {{ value|slugify }}
  1160. If ``value`` is ``"Joel is a slug"``, the output will be ``"joel-is-a-slug"``.
  1161. .. templatefilter:: stringformat
  1162. stringformat
  1163. ~~~~~~~~~~~~
  1164. Formats the variable according to the argument, a string formatting specifier.
  1165. This specifier uses Python string formatting syntax, with the exception that
  1166. the leading "%" is dropped.
  1167. See http://docs.python.org/library/stdtypes.html#string-formatting-operations
  1168. for documentation of Python string formatting
  1169. For example::
  1170. {{ value|stringformat:"s" }}
  1171. If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel is a slug"``.
  1172. .. templatefilter:: striptags
  1173. striptags
  1174. ~~~~~~~~~
  1175. Strips all [X]HTML tags.
  1176. For example::
  1177. {{ value|striptags }}
  1178. If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"``, the
  1179. output will be ``"Joel is a slug"``.
  1180. .. templatefilter:: time
  1181. time
  1182. ~~~~
  1183. Formats a time according to the given format.
  1184. Given format can be the predefined one ``TIME_FORMAT``, or a custom format,
  1185. same as the :ttag:`now` tag. Note that the predefined format is locale-
  1186. dependant.
  1187. The time filter will only accept parameters in the format string that relate
  1188. to the time of day, not the date (for obvious reasons). If you need to
  1189. format a date, use the :tfilter:`date` filter.
  1190. For example::
  1191. {{ value|time:"H:i" }}
  1192. If ``value`` is equivalent to ``datetime.datetime.now()``, the output will be
  1193. the string ``"01:23"``.
  1194. Another example:
  1195. Assuming that :setting:`USE_L10N` is ``True`` and :setting:`LANGUAGE_CODE` is,
  1196. for example, ``"de"``, then for::
  1197. {{ value|time:"TIME_FORMAT" }}
  1198. the output will be the string ``"01:23:00"`` (The ``"TIME_FORMAT"`` format
  1199. specifier for the ``de`` locale as shipped with Django is ``"H:i:s"``).
  1200. When used without a format string::
  1201. {{ value|time }}
  1202. ...the formatting string defined in the :setting:`TIME_FORMAT` setting will be
  1203. used, without applying any localization.
  1204. .. versionchanged:: 1.2
  1205. Predefined formats can now be influenced by the current locale.
  1206. .. templatefilter:: timesince
  1207. timesince
  1208. ~~~~~~~~~
  1209. Formats a date as the time since that date (e.g., "4 days, 6 hours").
  1210. Takes an optional argument that is a variable containing the date to use as
  1211. the comparison point (without the argument, the comparison point is *now*).
  1212. For example, if ``blog_date`` is a date instance representing midnight on 1
  1213. June 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006,
  1214. then ``{{ blog_date|timesince:comment_date }}`` would return "8 hours".
  1215. Comparing offset-naive and offset-aware datetimes will return an empty string.
  1216. Minutes is the smallest unit used, and "0 minutes" will be returned for any
  1217. date that is in the future relative to the comparison point.
  1218. .. templatefilter:: timeuntil
  1219. timeuntil
  1220. ~~~~~~~~~
  1221. Similar to ``timesince``, except that it measures the time from now until the
  1222. given date or datetime. For example, if today is 1 June 2006 and
  1223. ``conference_date`` is a date instance holding 29 June 2006, then
  1224. ``{{ conference_date|timeuntil }}`` will return "4 weeks".
  1225. Takes an optional argument that is a variable containing the date to use as
  1226. the comparison point (instead of *now*). If ``from_date`` contains 22 June
  1227. 2006, then ``{{ conference_date|timeuntil:from_date }}`` will return "1 week".
  1228. Comparing offset-naive and offset-aware datetimes will return an empty string.
  1229. Minutes is the smallest unit used, and "0 minutes" will be returned for any
  1230. date that is in the past relative to the comparison point.
  1231. .. templatefilter:: title
  1232. title
  1233. ~~~~~
  1234. Converts a string into titlecase.
  1235. For example::
  1236. {{ value|title }}
  1237. If ``value`` is ``"my first post"``, the output will be ``"My First Post"``.
  1238. .. templatefilter:: truncatewords
  1239. truncatewords
  1240. ~~~~~~~~~~~~~
  1241. Truncates a string after a certain number of words.
  1242. **Argument:** Number of words to truncate after
  1243. For example::
  1244. {{ value|truncatewords:2 }}
  1245. If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel is ..."``.
  1246. Newlines within the string will be removed.
  1247. .. templatefilter:: truncatewords_html
  1248. truncatewords_html
  1249. ~~~~~~~~~~~~~~~~~~
  1250. Similar to ``truncatewords``, except that it is aware of HTML tags. Any tags
  1251. that are opened in the string and not closed before the truncation point, are
  1252. closed immediately after the truncation.
  1253. This is less efficient than ``truncatewords``, so should only be used when it
  1254. is being passed HTML text.
  1255. For example::
  1256. {{ value|truncatewords_html:2 }}
  1257. If ``value`` is ``"<p>Joel is a slug</p>"``, the output will be
  1258. ``"<p>Joel is ...</p>"``.
  1259. Newlines in the HTML content will be preserved.
  1260. .. templatefilter:: unordered_list
  1261. unordered_list
  1262. ~~~~~~~~~~~~~~
  1263. Recursively takes a self-nested list and returns an HTML unordered list --
  1264. WITHOUT opening and closing <ul> tags.
  1265. .. versionchanged:: 1.0
  1266. The format accepted by ``unordered_list`` has changed to be easier to understand.
  1267. The list is assumed to be in the proper format. For example, if ``var`` contains
  1268. ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then
  1269. ``{{ var|unordered_list }}`` would return::
  1270. <li>States
  1271. <ul>
  1272. <li>Kansas
  1273. <ul>
  1274. <li>Lawrence</li>
  1275. <li>Topeka</li>
  1276. </ul>
  1277. </li>
  1278. <li>Illinois</li>
  1279. </ul>
  1280. </li>
  1281. Note: the previous more restrictive and verbose format is still supported:
  1282. ``['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]``,
  1283. .. templatefilter:: upper
  1284. upper
  1285. ~~~~~
  1286. Converts a string into all uppercase.
  1287. For example::
  1288. {{ value|upper }}
  1289. If ``value`` is ``"Joel is a slug"``, the output will be ``"JOEL IS A SLUG"``.
  1290. .. templatefilter:: urlencode
  1291. urlencode
  1292. ~~~~~~~~~
  1293. Escapes a value for use in a URL.
  1294. For example::
  1295. {{ value|urlencode }}
  1296. If ``value`` is ``"http://www.example.org/foo?a=b&c=d"``, the output will be
  1297. ``"http%3A//www.example.org/foo%3Fa%3Db%26c%3Dd"``.
  1298. .. templatefilter:: urlize
  1299. urlize
  1300. ~~~~~~
  1301. Converts URLs in plain text into clickable links.
  1302. Note that if ``urlize`` is applied to text that already contains HTML markup,
  1303. things won't work as expected. Apply this filter only to *plain* text.
  1304. For example::
  1305. {{ value|urlize }}
  1306. If ``value`` is ``"Check out www.djangoproject.com"``, the output will be
  1307. ``"Check out <a
  1308. href="http://www.djangoproject.com">www.djangoproject.com</a>"``.
  1309. .. templatefilter:: urlizetrunc
  1310. urlizetrunc
  1311. ~~~~~~~~~~~
  1312. Converts URLs into clickable links, truncating URLs longer than the given
  1313. character limit.
  1314. As with urlize_, this filter should only be applied to *plain* text.
  1315. **Argument:** Length to truncate URLs to
  1316. For example::
  1317. {{ value|urlizetrunc:15 }}
  1318. If ``value`` is ``"Check out www.djangoproject.com"``, the output would be
  1319. ``'Check out <a
  1320. href="http://www.djangoproject.com">www.djangopr...</a>'``.
  1321. .. templatefilter:: wordcount
  1322. wordcount
  1323. ~~~~~~~~~
  1324. Returns the number of words.
  1325. For example::
  1326. {{ value|wordcount }}
  1327. If ``value`` is ``"Joel is a slug"``, the output will be ``4``.
  1328. .. templatefilter:: wordwrap
  1329. wordwrap
  1330. ~~~~~~~~
  1331. Wraps words at specified line length.
  1332. **Argument:** number of characters at which to wrap the text
  1333. For example::
  1334. {{ value|wordwrap:5 }}
  1335. If ``value`` is ``Joel is a slug``, the output would be::
  1336. Joel
  1337. is a
  1338. slug
  1339. .. templatefilter:: yesno
  1340. yesno
  1341. ~~~~~
  1342. Given a string mapping values for true, false and (optionally) None,
  1343. returns one of those strings according to the value:
  1344. ========== ====================== ==================================
  1345. Value Argument Outputs
  1346. ========== ====================== ==================================
  1347. ``True`` ``"yeah,no,maybe"`` ``yeah``
  1348. ``False`` ``"yeah,no,maybe"`` ``no``
  1349. ``None`` ``"yeah,no,maybe"`` ``maybe``
  1350. ``None`` ``"yeah,no"`` ``"no"`` (converts None to False
  1351. if no mapping for None is given)
  1352. ========== ====================== ==================================
  1353. Other tags and filter libraries
  1354. -------------------------------
  1355. Django comes with a couple of other template-tag libraries that you have to
  1356. enable explicitly in your ``INSTALLED_APPS`` setting and enable in your
  1357. template with the ``{% load %}`` tag.
  1358. django.contrib.humanize
  1359. ~~~~~~~~~~~~~~~~~~~~~~~
  1360. A set of Django template filters useful for adding a "human touch" to data. See
  1361. :doc:`/ref/contrib/humanize`.
  1362. django.contrib.markup
  1363. ~~~~~~~~~~~~~~~~~~~~~
  1364. A collection of template filters that implement these common markup languages:
  1365. * Textile
  1366. * Markdown
  1367. * ReST (ReStructured Text)
  1368. See the :doc:`markup documentation </ref/contrib/markup>`.
  1369. django.contrib.webdesign
  1370. ~~~~~~~~~~~~~~~~~~~~~~~~
  1371. A collection of template tags that can be useful while designing a website,
  1372. such as a generator of Lorem Ipsum text. See :doc:`/ref/contrib/webdesign`.
  1373. i18n
  1374. ~~~~
  1375. Provides a couple of templatetags that allow specifying translatable text in
  1376. Django templates. It is slightly different from the libraries described
  1377. above because you don't need to add any application to the ``INSTALLED_APPS``
  1378. setting but rather set :setting:`USE_I18N` to True, then loading it with
  1379. ``{% load i18n %}``. See :ref:`specifying-translation-strings-in-template-code`.