builtins.txt 72 KB

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