builtins.txt 67 KB

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