builtins.txt 59 KB

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