builtins.txt 88 KB

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