builtins.txt 58 KB

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