builtins.txt 69 KB

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