builtins.txt 74 KB

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