builtins.txt 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574
  1. .. _ref-templates-builtins:
  2. ==================================
  3. Built-in template tags and filters
  4. ==================================
  5. This document describes Django's built-in template tags and filters. It is
  6. recommended that you use the :ref:`automatic documentation
  7. <template-built-in-reference>`, if available, as this will also include
  8. documentation for any custom tags or filters installed.
  9. .. _ref-templates-builtins-tags:
  10. Built-in tag reference
  11. ----------------------
  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.
  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. .. templatetag:: block
  27. block
  28. ~~~~~
  29. Define a block that can be overridden by child templates. See
  30. :ref:`Template inheritance <template-inheritance>` for more information.
  31. .. templatetag:: comment
  32. comment
  33. ~~~~~~~
  34. Ignore everything between ``{% comment %}`` and ``{% endcomment %}``
  35. .. templatetag:: cycle
  36. cycle
  37. ~~~~~
  38. .. versionchanged:: 1.0
  39. Cycle among the given strings or variables each time this tag is encountered.
  40. Within a loop, cycles among the given strings/variables each time through the
  41. loop::
  42. {% for o in some_list %}
  43. <tr class="{% cycle 'row1' 'row2' rowvar %}">
  44. ...
  45. </tr>
  46. {% endfor %}
  47. Outside of a loop, give the values a unique name the first time you call it,
  48. then use that name each successive time through::
  49. <tr class="{% cycle 'row1' 'row2' rowvar as rowcolors %}">...</tr>
  50. <tr class="{% cycle rowcolors %}">...</tr>
  51. <tr class="{% cycle rowcolors %}">...</tr>
  52. You can use any number of values, separated by spaces. Values enclosed in
  53. single (') or double quotes (") are treated as string literals, while values
  54. without quotes are assumed to refer to context variables.
  55. You can also separate values with commas::
  56. {% cycle row1,row2,row3 %}
  57. In this syntax, each value will be interpreted as literal text. The
  58. comma-based syntax exists for backwards-compatibility, and should not be
  59. used for new projects.
  60. .. templatetag:: debug
  61. debug
  62. ~~~~~
  63. Output a whole load of debugging information, including the current context and
  64. imported modules.
  65. .. templatetag:: extends
  66. extends
  67. ~~~~~~~
  68. Signal that this template extends a parent template.
  69. This tag can be used in two ways:
  70. * ``{% extends "base.html" %}`` (with quotes) uses the literal value
  71. ``"base.html"`` as the name of the parent template to extend.
  72. * ``{% extends variable %}`` uses the value of ``variable``. If the variable
  73. evaluates to a string, Django will use that string as the name of the
  74. parent template. If the variable evaluates to a ``Template`` object,
  75. Django will use that object as the parent template.
  76. See :ref:`template-inheritance` for more information.
  77. .. templatetag:: filter
  78. filter
  79. ~~~~~~
  80. Filter the contents of the variable through variable filters.
  81. Filters can also be piped through each other, and they can have arguments --
  82. just like in variable syntax.
  83. Sample usage::
  84. {% filter force_escape|lower %}
  85. This text will be HTML-escaped, and will appear in all lowercase.
  86. {% endfilter %}
  87. .. templatetag:: firstof
  88. firstof
  89. ~~~~~~~
  90. Outputs the first variable passed that is not False. Outputs nothing if all the
  91. passed variables are False.
  92. Sample usage::
  93. {% firstof var1 var2 var3 %}
  94. This is equivalent to::
  95. {% if var1 %}
  96. {{ var1 }}
  97. {% else %}{% if var2 %}
  98. {{ var2 }}
  99. {% else %}{% if var3 %}
  100. {{ var3 }}
  101. {% endif %}{% endif %}{% endif %}
  102. You can also use a literal string as a fallback value in case all
  103. passed variables are False::
  104. {% firstof var1 var2 var3 "fallback value" %}
  105. .. templatetag:: for
  106. for
  107. ~~~
  108. Loop over each item in an array. For example, to display a list of athletes
  109. provided in ``athlete_list``::
  110. <ul>
  111. {% for athlete in athlete_list %}
  112. <li>{{ athlete.name }}</li>
  113. {% endfor %}
  114. </ul>
  115. You can loop over a list in reverse by using ``{% for obj in list reversed %}``.
  116. .. versionadded:: 1.0
  117. If you need to loop over a list of lists, you can unpack the values
  118. in each sub-list into individual variables. For example, if your context
  119. contains a list of (x,y) coordinates called ``points``, you could use the
  120. following to output the list of points::
  121. {% for x, y in points %}
  122. There is a point at {{ x }},{{ y }}
  123. {% endfor %}
  124. This can also be useful if you need to access the items in a dictionary.
  125. For example, if your context contained a dictionary ``data``, the following
  126. would display the keys and values of the dictionary::
  127. {% for key, value in data.items %}
  128. {{ key }}: {{ value }}
  129. {% endfor %}
  130. The for loop sets a number of variables available within the loop:
  131. ========================== ================================================
  132. Variable Description
  133. ========================== ================================================
  134. ``forloop.counter`` The current iteration of the loop (1-indexed)
  135. ``forloop.counter0`` The current iteration of the loop (0-indexed)
  136. ``forloop.revcounter`` The number of iterations from the end of the
  137. loop (1-indexed)
  138. ``forloop.revcounter0`` The number of iterations from the end of the
  139. loop (0-indexed)
  140. ``forloop.first`` True if this is the first time through the loop
  141. ``forloop.last`` True if this is the last time through the loop
  142. ``forloop.parentloop`` For nested loops, this is the loop "above" the
  143. current one
  144. ========================== ================================================
  145. .. templatetag:: if
  146. if
  147. ~~
  148. The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e.
  149. exists, is not empty, and is not a false boolean value) the contents of the
  150. block are output::
  151. {% if athlete_list %}
  152. Number of athletes: {{ athlete_list|length }}
  153. {% else %}
  154. No athletes.
  155. {% endif %}
  156. In the above, if ``athlete_list`` is not empty, the number of athletes will be
  157. displayed by the ``{{ athlete_list|length }}`` variable.
  158. As you can see, the ``if`` tag can take an optional ``{% else %}`` clause that
  159. will be displayed if the test fails.
  160. ``if`` tags may use ``and``, ``or`` or ``not`` to test a number of variables or
  161. to negate a given variable::
  162. {% if athlete_list and coach_list %}
  163. Both athletes and coaches are available.
  164. {% endif %}
  165. {% if not athlete_list %}
  166. There are no athletes.
  167. {% endif %}
  168. {% if athlete_list or coach_list %}
  169. There are some athletes or some coaches.
  170. {% endif %}
  171. {% if not athlete_list or coach_list %}
  172. There are no athletes or there are some coaches (OK, so
  173. writing English translations of boolean logic sounds
  174. stupid; it's not our fault).
  175. {% endif %}
  176. {% if athlete_list and not coach_list %}
  177. There are some athletes and absolutely no coaches.
  178. {% endif %}
  179. ``if`` tags don't allow ``and`` and ``or`` clauses within the same tag, because
  180. the order of logic would be ambiguous. For example, this is invalid::
  181. {% if athlete_list and coach_list or cheerleader_list %}
  182. If you need to combine ``and`` and ``or`` to do advanced logic, just use nested
  183. ``if`` tags. For example::
  184. {% if athlete_list %}
  185. {% if coach_list or cheerleader_list %}
  186. We have athletes, and either coaches or cheerleaders!
  187. {% endif %}
  188. {% endif %}
  189. Multiple uses of the same logical operator are fine, as long as you use the
  190. same operator. For example, this is valid::
  191. {% if athlete_list or coach_list or parent_list or teacher_list %}
  192. .. templatetag:: ifchanged
  193. ifchanged
  194. ~~~~~~~~~
  195. Check if a value has changed from the last iteration of a loop.
  196. The 'ifchanged' block tag is used within a loop. It has two possible uses.
  197. 1. Checks its own rendered contents against its previous state and only
  198. displays the content if it has changed. For example, this displays a list of
  199. days, only displaying the month if it changes::
  200. <h1>Archive for {{ year }}</h1>
  201. {% for date in days %}
  202. {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
  203. <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
  204. {% endfor %}
  205. 2. If given a variable, check whether that variable has changed. For
  206. example, the following shows the date every time it changes, but
  207. only shows the hour if both the hour and the date has changed::
  208. {% for date in days %}
  209. {% ifchanged date.date %} {{ date.date }} {% endifchanged %}
  210. {% ifchanged date.hour date.date %}
  211. {{ date.hour }}
  212. {% endifchanged %}
  213. {% endfor %}
  214. .. templatetag:: ifequal
  215. ifequal
  216. ~~~~~~~
  217. Output the contents of the block if the two arguments equal each other.
  218. Example::
  219. {% ifequal user.id comment.user_id %}
  220. ...
  221. {% endifequal %}
  222. As in the ``{% if %}`` tag, an ``{% else %}`` clause is optional.
  223. The arguments can be hard-coded strings, so the following is valid::
  224. {% ifequal user.username "adrian" %}
  225. ...
  226. {% endifequal %}
  227. It is only possible to compare an argument to template variables or strings.
  228. You cannot check for equality with Python objects such as ``True`` or
  229. ``False``. If you need to test if something is true or false, use the ``if``
  230. tag instead.
  231. .. templatetag:: ifnotequal
  232. ifnotequal
  233. ~~~~~~~~~~
  234. Just like ``ifequal``, except it tests that the two arguments are not equal.
  235. .. templatetag:: include
  236. include
  237. ~~~~~~~
  238. Loads a template and renders it with the current context. This is a way of
  239. "including" other templates within a template.
  240. The template name can either be a variable or a hard-coded (quoted) string,
  241. in either single or double quotes.
  242. This example includes the contents of the template ``"foo/bar.html"``::
  243. {% include "foo/bar.html" %}
  244. This example includes the contents of the template whose name is contained in
  245. the variable ``template_name``::
  246. {% include template_name %}
  247. An included template is rendered with the context of the template that's
  248. including it. This example produces the output ``"Hello, John"``:
  249. * Context: variable ``person`` is set to ``"john"``.
  250. * Template::
  251. {% include "name_snippet.html" %}
  252. * The ``name_snippet.html`` template::
  253. Hello, {{ person }}
  254. See also: ``{% ssi %}``.
  255. .. templatetag:: load
  256. load
  257. ~~~~
  258. Load a custom template tag set.
  259. See :ref:`Custom tag and filter libraries <howto-custom-template-tags>` for more information.
  260. .. templatetag:: now
  261. now
  262. ~~~
  263. Display the date, formatted according to the given string.
  264. Uses the same format as PHP's ``date()`` function (http://php.net/date)
  265. with some custom extensions.
  266. Available format strings:
  267. ================ ======================================== =====================
  268. Format character Description Example output
  269. ================ ======================================== =====================
  270. a ``'a.m.'`` or ``'p.m.'`` (Note that ``'a.m.'``
  271. this is slightly different than PHP's
  272. output, because this includes periods
  273. to match Associated Press style.)
  274. A ``'AM'`` or ``'PM'``. ``'AM'``
  275. b Month, textual, 3 letters, lowercase. ``'jan'``
  276. B Not implemented.
  277. d Day of the month, 2 digits with ``'01'`` to ``'31'``
  278. leading zeros.
  279. D Day of the week, textual, 3 letters. ``'Fri'``
  280. f Time, in 12-hour hours and minutes, ``'1'``, ``'1:30'``
  281. with minutes left off if they're zero.
  282. Proprietary extension.
  283. F Month, textual, long. ``'January'``
  284. g Hour, 12-hour format without leading ``'1'`` to ``'12'``
  285. zeros.
  286. G Hour, 24-hour format without leading ``'0'`` to ``'23'``
  287. zeros.
  288. h Hour, 12-hour format. ``'01'`` to ``'12'``
  289. H Hour, 24-hour format. ``'00'`` to ``'23'``
  290. i Minutes. ``'00'`` to ``'59'``
  291. I Not implemented.
  292. j Day of the month without leading ``'1'`` to ``'31'``
  293. zeros.
  294. l Day of the week, textual, long. ``'Friday'``
  295. L Boolean for whether it's a leap year. ``True`` or ``False``
  296. m Month, 2 digits with leading zeros. ``'01'`` to ``'12'``
  297. M Month, textual, 3 letters. ``'Jan'``
  298. n Month without leading zeros. ``'1'`` to ``'12'``
  299. N Month abbreviation in Associated Press ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'``
  300. style. Proprietary extension.
  301. O Difference to Greenwich time in hours. ``'+0200'``
  302. P Time, in 12-hour hours, minutes and ``'1 a.m.'``, ``'1:30 p.m.'``, ``'midnight'``, ``'noon'``, ``'12:30 p.m.'``
  303. 'a.m.'/'p.m.', with minutes left off
  304. if they're zero and the special-case
  305. strings 'midnight' and 'noon' if
  306. appropriate. Proprietary extension.
  307. r RFC 2822 formatted date. ``'Thu, 21 Dec 2000 16:01:07 +0200'``
  308. s Seconds, 2 digits with leading zeros. ``'00'`` to ``'59'``
  309. S English ordinal suffix for day of the ``'st'``, ``'nd'``, ``'rd'`` or ``'th'``
  310. month, 2 characters.
  311. t Number of days in the given month. ``28`` to ``31``
  312. T Time zone of this machine. ``'EST'``, ``'MDT'``
  313. U Not implemented.
  314. w Day of the week, digits without ``'0'`` (Sunday) to ``'6'`` (Saturday)
  315. leading zeros.
  316. W ISO-8601 week number of year, with ``1``, ``53``
  317. weeks starting on Monday.
  318. y Year, 2 digits. ``'99'``
  319. Y Year, 4 digits. ``'1999'``
  320. z Day of the year. ``0`` to ``365``
  321. Z Time zone offset in seconds. The ``-43200`` to ``43200``
  322. offset for timezones west of UTC is
  323. always negative, and for those east of
  324. UTC is always positive.
  325. ================ ======================================== =====================
  326. Example::
  327. It is {% now "jS F Y H:i" %}
  328. Note that you can backslash-escape a format string if you want to use the
  329. "raw" value. In this example, "f" is backslash-escaped, because otherwise
  330. "f" is a format string that displays the time. The "o" doesn't need to be
  331. escaped, because it's not a format character::
  332. It is the {% now "jS o\f F" %}
  333. This would display as "It is the 4th of September".
  334. .. templatetag:: regroup
  335. regroup
  336. ~~~~~~~
  337. Regroup a list of alike objects by a common attribute.
  338. This complex tag is best illustrated by use of an example: say that ``people``
  339. is a list of people represented by dictionaries with ``first_name``,
  340. ``last_name``, and ``gender`` keys::
  341. people = [
  342. {'first_name': 'George', 'last_name': 'Bush', 'gender': 'Male'},
  343. {'first_name': 'Bill', 'last_name': 'Clinton', 'gender': 'Male'},
  344. {'first_name': 'Margaret', 'last_name': 'Thatcher', 'gender': 'Female'},
  345. {'first_name': 'Condoleezza', 'last_name': 'Rice', 'gender': 'Female'},
  346. {'first_name': 'Pat', 'last_name': 'Smith', 'gender': 'Unknown'},
  347. ]
  348. ...and you'd like to display a hierarchical list that is ordered by gender,
  349. like this:
  350. * Male:
  351. * George Bush
  352. * Bill Clinton
  353. * Female:
  354. * Margaret Thatcher
  355. * Condoleezza Rice
  356. * Unknown:
  357. * Pat Smith
  358. You can use the ``{% regroup %}`` tag to group the list of people by gender.
  359. The following snippet of template code would accomplish this::
  360. {% regroup people by gender as gender_list %}
  361. <ul>
  362. {% for gender in gender_list %}
  363. <li>{{ gender.grouper }}
  364. <ul>
  365. {% for item in gender.list %}
  366. <li>{{ item.first_name }} {{ item.last_name }}</li>
  367. {% endfor %}
  368. </ul>
  369. </li>
  370. {% endfor %}
  371. </ul>
  372. Let's walk through this example. ``{% regroup %}`` takes three arguments: the
  373. list you want to regroup, the attribute to group by, and the name of the
  374. resulting list. Here, we're regrouping the ``people`` list by the ``gender``
  375. attribute and calling the result ``gender_list``.
  376. ``{% regroup %}`` produces a list (in this case, ``gender_list``) of
  377. **group objects**. Each group object has two attributes:
  378. * ``grouper`` -- the item that was grouped by (e.g., the string "Male" or
  379. "Female").
  380. * ``list`` -- a list of all items in this group (e.g., a list of all people
  381. with gender='Male').
  382. Note that ``{% regroup %}`` does not order its input! Our example relies on
  383. the fact that the ``people`` list was ordered by ``gender`` in the first place.
  384. If the ``people`` list did *not* order its members by ``gender``, the regrouping
  385. would naively display more than one group for a single gender. For example,
  386. say the ``people`` list was set to this (note that the males are not grouped
  387. together)::
  388. people = [
  389. {'first_name': 'Bill', 'last_name': 'Clinton', 'gender': 'Male'},
  390. {'first_name': 'Pat', 'last_name': 'Smith', 'gender': 'Unknown'},
  391. {'first_name': 'Margaret', 'last_name': 'Thatcher', 'gender': 'Female'},
  392. {'first_name': 'George', 'last_name': 'Bush', 'gender': 'Male'},
  393. {'first_name': 'Condoleezza', 'last_name': 'Rice', 'gender': 'Female'},
  394. ]
  395. With this input for ``people``, the example ``{% regroup %}`` template code
  396. above would result in the following output:
  397. * Male:
  398. * Bill Clinton
  399. * Unknown:
  400. * Pat Smith
  401. * Female:
  402. * Margaret Thatcher
  403. * Male:
  404. * George Bush
  405. * Female:
  406. * Condoleezza Rice
  407. The easiest solution to this gotcha is to make sure in your view code that the
  408. data is ordered according to how you want to display it.
  409. Another solution is to sort the data in the template using the ``dictsort``
  410. filter, if your data is in a list of dictionaries::
  411. {% regroup people|dictsort:"gender" by gender as gender_list %}
  412. .. templatetag:: spaceless
  413. spaceless
  414. ~~~~~~~~~
  415. Removes whitespace between HTML tags. This includes tab
  416. characters and newlines.
  417. Example usage::
  418. {% spaceless %}
  419. <p>
  420. <a href="foo/">Foo</a>
  421. </p>
  422. {% endspaceless %}
  423. This example would return this HTML::
  424. <p><a href="foo/">Foo</a></p>
  425. Only space between *tags* is removed -- not space between tags and text. In
  426. this example, the space around ``Hello`` won't be stripped::
  427. {% spaceless %}
  428. <strong>
  429. Hello
  430. </strong>
  431. {% endspaceless %}
  432. .. templatetag:: ssi
  433. ssi
  434. ~~~
  435. Output the contents of a given file into the page.
  436. Like a simple "include" tag, ``{% ssi %}`` includes the contents of another
  437. file -- which must be specified using an absolute path -- in the current
  438. page::
  439. {% ssi /home/html/ljworld.com/includes/right_generic.html %}
  440. If the optional "parsed" parameter is given, the contents of the included
  441. file are evaluated as template code, within the current context::
  442. {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %}
  443. Note that if you use ``{% ssi %}``, you'll need to define
  444. :setting:`ALLOWED_INCLUDE_ROOTS` in your Django settings, as a security measure.
  445. See also: ``{% include %}``.
  446. .. templatetag:: templatetag
  447. templatetag
  448. ~~~~~~~~~~~
  449. Output one of the syntax characters used to compose template tags.
  450. Since the template system has no concept of "escaping", to display one of the
  451. bits used in template tags, you must use the ``{% templatetag %}`` tag.
  452. The argument tells which template bit to output:
  453. ================== =======
  454. Argument Outputs
  455. ================== =======
  456. ``openblock`` ``{%``
  457. ``closeblock`` ``%}``
  458. ``openvariable`` ``{{``
  459. ``closevariable`` ``}}``
  460. ``openbrace`` ``{``
  461. ``closebrace`` ``}``
  462. ``opencomment`` ``{#``
  463. ``closecomment`` ``#}``
  464. ================== =======
  465. .. templatetag:: url
  466. url
  467. ~~~
  468. Returns an absolute URL (i.e., a URL without the domain name) matching a given
  469. view function and optional parameters. This is a way to output links without
  470. violating the DRY principle by having to hard-code URLs in your templates::
  471. {% url path.to.some_view arg1,arg2,name1=value1 %}
  472. The first argument is a path to a view function in the format
  473. ``package.package.module.function``. Additional arguments are optional and
  474. should be comma-separated values that will be used as positional and keyword
  475. arguments in the URL. All arguments required by the URLconf should be present.
  476. For example, suppose you have a view, ``app_views.client``, whose URLconf
  477. takes a client ID (here, ``client()`` is a method inside the views file
  478. ``app_views.py``). The URLconf line might look like this::
  479. ('^client/(\d+)/$', 'app_views.client')
  480. If this app's URLconf is included into the project's URLconf under a path
  481. such as this::
  482. ('^clients/', include('project_name.app_name.urls'))
  483. ...then, in a template, you can create a link to this view like this::
  484. {% url app_views.client client.id %}
  485. The template tag will output the string ``/clients/client/123/``.
  486. .. versionadded:: 1.0
  487. If you're using :ref:`named URL patterns <naming-url-patterns>`, you can
  488. refer to the name of the pattern in the ``url`` tag instead of using the
  489. path to the view.
  490. Note that if the URL you're reversing doesn't exist, you'll get an
  491. :exc:`NoReverseMatch` exception raised, which will cause your site to display an
  492. error page.
  493. **New in development verson:** If you'd like to retrieve a URL without displaying it,
  494. you can use a slightly different call:
  495. .. code-block:: html+django
  496. {% url path.to.view arg, arg2 as the_url %}
  497. <a href="{{ the_url }}">I'm linking to {{ the_url }}</a>
  498. This ``{% url ... as var %}`` syntax will *not* cause an error if the view is
  499. missing. In practice you'll use this to link to views that are optional:
  500. .. code-block:: html+django
  501. {% url path.to.view as the_url %}
  502. {% if the_url %}
  503. <a href="{{ the_url }}">Link to optional stuff</a>
  504. {% endif %}
  505. .. templatetag:: widthratio
  506. widthratio
  507. ~~~~~~~~~~
  508. For creating bar charts and such, this tag calculates the ratio of a given value
  509. to a maximum value, and then applies that ratio to a constant.
  510. For example::
  511. <img src="bar.gif" height="10" width="{% widthratio this_value max_value 100 %}" />
  512. Above, if ``this_value`` is 175 and ``max_value`` is 200, the image in the
  513. above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5
  514. which is rounded up to 88).
  515. .. templatetag:: with
  516. with
  517. ~~~~
  518. .. versionadded:: 1.0
  519. Caches a complex variable under a simpler name. This is useful when accessing
  520. an "expensive" method (e.g., one that hits the database) multiple times.
  521. For example::
  522. {% with business.employees.count as total %}
  523. {{ total }} employee{{ total|pluralize }}
  524. {% endwith %}
  525. The populated variable (in the example above, ``total``) is only available
  526. between the ``{% with %}`` and ``{% endwith %}`` tags.
  527. .. _ref-templates-builtins-filters:
  528. Built-in filter reference
  529. -------------------------
  530. .. templatefilter:: add
  531. add
  532. ~~~
  533. Adds the argument to the value.
  534. For example::
  535. {{ value|add:"2" }}
  536. If ``value`` is ``4``, then the output will be ``6``.
  537. .. templatefilter:: addslashes
  538. addslashes
  539. ~~~~~~~~~~
  540. Adds slashes before quotes. Useful for escaping strings in CSV, for example.
  541. .. templatefilter:: capfirst
  542. capfirst
  543. ~~~~~~~~
  544. Capitalizes the first character of the value.
  545. .. templatefilter:: center
  546. center
  547. ~~~~~~
  548. Centers the value in a field of a given width.
  549. .. templatefilter:: cut
  550. cut
  551. ~~~
  552. Removes all values of arg from the given string.
  553. For example::
  554. {{ value|cut:" "}}
  555. If ``value`` is ``"String with spaces"``, the output will be ``"Stringwithspaces"``.
  556. .. templatefilter:: date
  557. date
  558. ~~~~
  559. Formats a date according to the given format (same as the `now`_ tag).
  560. For example::
  561. {{ value|date:"D d M Y" }}
  562. If ``value`` is a ``datetime`` object (e.g., the result of
  563. ``datetime.datetime.now()``), the output will be the string
  564. ``'Wed 09 Jan 2008'``.
  565. .. templatefilter:: default
  566. default
  567. ~~~~~~~
  568. If value evaluates to ``False``, use given default. Otherwise, use the value.
  569. For example::
  570. {{ value|default:"nothing" }}
  571. If ``value`` is ``""`` (the empty string), the output will be ``nothing``.
  572. .. templatefilter:: default_if_none
  573. default_if_none
  574. ~~~~~~~~~~~~~~~
  575. If (and only if) value is ``None``, use given default. Otherwise, use the
  576. value.
  577. Note that if an empty string is given, the default value will *not* be used.
  578. Use the ``default`` filter if you want to fallback for empty strings.
  579. For example::
  580. {{ value|default_if_none:"nothing" }}
  581. If ``value`` is ``None``, the output will be the string ``"nothing"``.
  582. .. templatefilter:: dictsort
  583. dictsort
  584. ~~~~~~~~
  585. Takes a list of dictionaries and returns that list sorted by the key given in
  586. the argument.
  587. For example::
  588. {{ value|dictsort:"name" }}
  589. If ``value`` is::
  590. [
  591. {'name': 'zed', 'age': 19},
  592. {'name': 'amy', 'age': 22},
  593. {'name': 'joe', 'age': 31},
  594. ]
  595. then the output would be::
  596. [
  597. {'name': 'amy', 'age': 22},
  598. {'name': 'joe', 'age': 31},
  599. {'name': 'zed', 'age': 19},
  600. ]
  601. .. templatefilter:: dictsortreversed
  602. dictsortreversed
  603. ~~~~~~~~~~~~~~~~
  604. Takes a list of dictionaries and returns that list sorted in reverse order by
  605. the key given in the argument. This works exactly the same as the above filter,
  606. but the returned value will be in reverse order.
  607. .. templatefilter:: divisibleby
  608. divisibleby
  609. ~~~~~~~~~~~
  610. Returns ``True`` if the value is divisible by the argument.
  611. For example::
  612. {{ value|divisibleby:"3" }}
  613. If ``value`` is ``21``, the output would be ``True``.
  614. .. templatefilter:: escape
  615. escape
  616. ~~~~~~
  617. Escapes a string's HTML. Specifically, it makes these replacements:
  618. * ``<`` is converted to ``&lt;``
  619. * ``>`` is converted to ``&gt;``
  620. * ``'`` (single quote) is converted to ``&#39;``
  621. * ``"`` (double quote) is converted to ``&quot;``
  622. * ``&`` is converted to ``&amp;``
  623. The escaping is only applied when the string is output, so it does not matter
  624. where in a chained sequence of filters you put ``escape``: it will always be
  625. applied as though it were the last filter. If you want escaping to be applied
  626. immediately, use the ``force_escape`` filter.
  627. Applying ``escape`` to a variable that would normally have auto-escaping
  628. applied to the result will only result in one round of escaping being done. So
  629. it is safe to use this function even in auto-escaping environments. If you want
  630. multiple escaping passes to be applied, use the ``force_escape`` filter.
  631. .. versionchanged:: 1.0
  632. Due to auto-escaping, the behavior of this filter has changed slightly.
  633. The replacements are only made once, after
  634. all other filters are applied -- including filters before and after it.
  635. .. templatefilter:: escapejs
  636. escapejs
  637. ~~~~~~~~
  638. .. versionadded:: 1.0
  639. Escapes characters for use in JavaScript strings. This does *not* make the
  640. string safe for use in HTML, but does protect you from syntax errors when using
  641. templates to generate JavaScript/JSON.
  642. .. templatefilter:: filesizeformat
  643. filesizeformat
  644. ~~~~~~~~~~~~~~
  645. Format the value like a 'human-readable' file size (i.e. ``'13 KB'``,
  646. ``'4.1 MB'``, ``'102 bytes'``, etc).
  647. For example::
  648. {{ value|filesizeformat }}
  649. If ``value`` is 123456789, the output would be ``117.7 MB``.
  650. .. templatefilter:: first
  651. first
  652. ~~~~~
  653. Returns the first item in a list.
  654. For example::
  655. {{ value|first }}
  656. If ``value`` is the list ``['a', 'b', 'c']``, the output will be ``'a'``.
  657. .. templatefilter:: fix_ampersands
  658. fix_ampersands
  659. ~~~~~~~~~~~~~~
  660. .. versionchanged:: 1.0
  661. This is rarely useful as ampersands are now automatically escaped. See escape_ for more information.
  662. Replaces ampersands with ``&amp;`` entities.
  663. For example::
  664. {{ value|fix_ampersands }}
  665. If ``value`` is ``Tom & Jerry``, the output will be ``Tom &amp; Jerry``.
  666. .. templatefilter:: floatformat
  667. floatformat
  668. ~~~~~~~~~~~
  669. When used without an argument, rounds a floating-point number to one decimal
  670. place -- but only if there's a decimal part to be displayed. For example:
  671. ============ =========================== ========
  672. ``value`` Template Output
  673. ============ =========================== ========
  674. ``34.23234`` ``{{ value|floatformat }}`` ``34.2``
  675. ``34.00000`` ``{{ value|floatformat }}`` ``34``
  676. ``34.26000`` ``{{ value|floatformat }}`` ``34.3``
  677. ============ =========================== ========
  678. If used with a numeric integer argument, ``floatformat`` rounds a number to
  679. that many decimal places. For example:
  680. ============ ============================= ==========
  681. ``value`` Template Output
  682. ============ ============================= ==========
  683. ``34.23234`` ``{{ value|floatformat:3 }}`` ``34.232``
  684. ``34.00000`` ``{{ value|floatformat:3 }}`` ``34.000``
  685. ``34.26000`` ``{{ value|floatformat:3 }}`` ``34.260``
  686. ============ ============================= ==========
  687. If the argument passed to ``floatformat`` is negative, it will round a number
  688. to that many decimal places -- but only if there's a decimal part to be
  689. displayed. For example:
  690. ============ ================================ ==========
  691. ``value`` Template Output
  692. ============ ================================ ==========
  693. ``34.23234`` ``{{ value|floatformat:"-3" }}`` ``34.232``
  694. ``34.00000`` ``{{ value|floatformat:"-3" }}`` ``34``
  695. ``34.26000`` ``{{ value|floatformat:"-3" }}`` ``34.260``
  696. ============ ================================ ==========
  697. Using ``floatformat`` with no argument is equivalent to using ``floatformat``
  698. with an argument of ``-1``.
  699. .. templatefilter:: force_escape
  700. force_escape
  701. ~~~~~~~~~~~~
  702. .. versionadded:: 1.0
  703. Applies HTML escaping to a string (see the ``escape`` filter for details).
  704. This filter is applied *immediately* and returns a new, escaped string. This
  705. is useful in the rare cases where you need multiple escaping or want to apply
  706. other filters to the escaped results. Normally, you want to use the ``escape``
  707. filter.
  708. .. templatefilter:: get_digit
  709. get_digit
  710. ~~~~~~~~~
  711. Given a whole number, returns the requested digit, where 1 is the right-most
  712. digit, 2 is the second-right-most digit, etc. Returns the original value for
  713. invalid input (if input or argument is not an integer, or if argument is less
  714. than 1). Otherwise, output is always an integer.
  715. For example::
  716. {{ value|get_digit:"2" }}
  717. If ``value`` is ``123456789``, the output will be ``8``.
  718. .. templatefilter:: iriendcode
  719. iriencode
  720. ~~~~~~~~~
  721. Converts an IRI (Internationalized Resource Identifier) to a string that is
  722. suitable for including in a URL. This is necessary if you're trying to use
  723. strings containing non-ASCII characters in a URL.
  724. It's safe to use this filter on a string that has already gone through the
  725. ``urlencode`` filter.
  726. .. templatefilter:: join
  727. join
  728. ~~~~
  729. Joins a list with a string, like Python's ``str.join(list)``
  730. For example::
  731. {{ value|join:" // " }}
  732. If ``value`` is the list ``['a', 'b', 'c']``, the output will be the string
  733. ``"a // b // c"``.
  734. .. templatefilter:: last
  735. last
  736. ~~~~
  737. .. versionadded:: 1.0
  738. Returns the last item in a list.
  739. For example::
  740. {{ value|last }}
  741. If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output will be the string
  742. ``"d"``.
  743. .. templatefilter:: length
  744. length
  745. ~~~~~~
  746. Returns the length of the value. This works for both strings and lists.
  747. For example::
  748. {{ value|length }}
  749. If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``4``.
  750. .. templatefilter:: length_is
  751. length_is
  752. ~~~~~~~~~
  753. Returns ``True`` if the value's length is the argument, or ``False`` otherwise.
  754. For example::
  755. {{ value|length_is:"4" }}
  756. If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``True``.
  757. .. templatefilter:: linebreaks
  758. linebreaks
  759. ~~~~~~~~~~
  760. Replaces line breaks in plain text with appropriate HTML; a single
  761. newline becomes an HTML line break (``<br />``) and a new line
  762. followed by a blank line becomes a paragraph break (``</p>``).
  763. For example::
  764. {{ value|linebreaks }}
  765. If ``value`` is ``Joel\nis a slug``, the output will be ``<p>Joel<br>is a
  766. slug</p>``.
  767. .. templatefilter:: linebreaksbr
  768. linebreaksbr
  769. ~~~~~~~~~~~~
  770. Converts all newlines in a piece of plain text to HTML line breaks
  771. (``<br />``).
  772. .. templatefilter:: linenumbers
  773. linenumbers
  774. ~~~~~~~~~~~
  775. Displays text with line numbers.
  776. .. templatefilter:: ljust
  777. ljust
  778. ~~~~~
  779. Left-aligns the value in a field of a given width.
  780. **Argument:** field size
  781. .. templatefilter:: lower
  782. lower
  783. ~~~~~
  784. Converts a string into all lowercase.
  785. For example::
  786. {{ value|lower }}
  787. If ``value`` is ``Still MAD At Yoko``, the output will be ``still mad at yoko``.
  788. .. templatefilter:: make_list
  789. make_list
  790. ~~~~~~~~~
  791. Returns the value turned into a list. For an integer, it's a list of
  792. digits. For a string, it's a list of characters.
  793. For example::
  794. {{ value|make_list }}
  795. If ``value`` is the string ``"Joel"``, the output would be the list
  796. ``[u'J', u'o', u'e', u'l']``. If ``value`` is ``123``, the output will be the
  797. list ``[1, 2, 3]``.
  798. .. templatefilter:: phone2numeric
  799. phone2numeric
  800. ~~~~~~~~~~~~~
  801. Converts a phone number (possibly containing letters) to its numerical
  802. equivalent. For example, ``'800-COLLECT'`` will be converted to
  803. ``'800-2655328'``.
  804. The input doesn't have to be a valid phone number. This will happily convert
  805. any string.
  806. .. templatefilter:: pluralize
  807. pluralize
  808. ~~~~~~~~~
  809. Returns a plural suffix if the value is not 1. By default, this suffix is ``'s'``.
  810. Example::
  811. You have {{ num_messages }} message{{ num_messages|pluralize }}.
  812. For words that require a suffix other than ``'s'``, you can provide an alternate
  813. suffix as a parameter to the filter.
  814. Example::
  815. You have {{ num_walruses }} walrus{{ num_walrus|pluralize:"es" }}.
  816. For words that don't pluralize by simple suffix, you can specify both a
  817. singular and plural suffix, separated by a comma.
  818. Example::
  819. You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.
  820. .. templatefilter:: pprint
  821. pprint
  822. ~~~~~~
  823. A wrapper around `pprint.pprint`__ -- for debugging, really.
  824. __ http://www.python.org/doc/2.5/lib/module-pprint.html
  825. .. templatefilter:: random
  826. random
  827. ~~~~~~
  828. Returns a random item from the given list.
  829. For example::
  830. {{ value|random }}
  831. If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output could be ``"b"``.
  832. .. templatefilter:: removetags
  833. removetags
  834. ~~~~~~~~~~
  835. Removes a space-separated list of [X]HTML tags from the output.
  836. For example::
  837. {{ value|removetags:"b span"|safe }}
  838. If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"`` the
  839. output will be ``"Joel <button>is</button> a slug"``.
  840. .. templatefilter:: rjust
  841. rjust
  842. ~~~~~
  843. Right-aligns the value in a field of a given width.
  844. **Argument:** field size
  845. .. templatefilter:: safe
  846. safe
  847. ~~~~
  848. Marks a string as not requiring further HTML escaping prior to output. When
  849. autoescaping is off, this filter has no effect.
  850. .. templatefilter:: slice
  851. slice
  852. ~~~~~
  853. Returns a slice of the list.
  854. Uses the same syntax as Python's list slicing. See
  855. http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice
  856. for an introduction.
  857. Example: ``{{ some_list|slice:":2" }}``
  858. .. templatefilter:: slugify
  859. slugify
  860. ~~~~~~~
  861. Converts to lowercase, removes non-word characters (alphanumerics and
  862. underscores) and converts spaces to hyphens. Also strips leading and trailing
  863. whitespace.
  864. For example::
  865. {{ value|slugify }}
  866. If ``value`` is ``"Joel is a slug"``, the output will be ``"joel-is-a-slug"``.
  867. .. templatefilter:: stringformat
  868. stringformat
  869. ~~~~~~~~~~~~
  870. Formats the variable according to the argument, a string formatting specifier.
  871. This specifier uses Python string formatting syntax, with the exception that
  872. the leading "%" is dropped.
  873. See http://docs.python.org/lib/typesseq-strings.html for documentation of
  874. Python string formatting
  875. For example::
  876. {{ value|stringformat:"s" }}
  877. If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel is a slug"``.
  878. .. templatefilter:: striptags
  879. striptags
  880. ~~~~~~~~~
  881. Strips all [X]HTML tags.
  882. For example::
  883. {{ value|striptags }}
  884. If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"``, the
  885. output will be ``"Joel is a slug"``.
  886. .. templatefilter:: time
  887. time
  888. ~~~~
  889. Formats a time according to the given format (same as the `now`_ tag).
  890. The time filter will only accept parameters in the format string that relate
  891. to the time of day, not the date (for obvious reasons). If you need to
  892. format a date, use the `date`_ filter.
  893. For example::
  894. {{ value|time:"H:i" }}
  895. If ``value`` is equivalent to ``datetime.datetime.now()``, the output will be
  896. the string ``"01:23"``.
  897. .. templatefilter:: timesince
  898. timesince
  899. ~~~~~~~~~
  900. Formats a date as the time since that date (e.g., "4 days, 6 hours").
  901. Takes an optional argument that is a variable containing the date to use as
  902. the comparison point (without the argument, the comparison point is *now*).
  903. For example, if ``blog_date`` is a date instance representing midnight on 1
  904. June 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006,
  905. then ``{{ blog_date|timesince:comment_date }}`` would return "8 hours".
  906. Comparing offset-naive and offset-aware datetimes will return an empty string.
  907. Minutes is the smallest unit used, and "0 minutes" will be returned for any
  908. date that is in the future relative to the comparison point.
  909. .. templatefilter:: timeuntil
  910. timeuntil
  911. ~~~~~~~~~
  912. Similar to ``timesince``, except that it measures the time from now until the
  913. given date or datetime. For example, if today is 1 June 2006 and
  914. ``conference_date`` is a date instance holding 29 June 2006, then
  915. ``{{ conference_date|timeuntil }}`` will return "4 weeks".
  916. Takes an optional argument that is a variable containing the date to use as
  917. the comparison point (instead of *now*). If ``from_date`` contains 22 June
  918. 2006, then ``{{ conference_date|timeuntil:from_date }}`` will return "1 week".
  919. Comparing offset-naive and offset-aware datetimes will return an empty string.
  920. Minutes is the smallest unit used, and "0 minutes" will be returned for any
  921. date that is in the past relative to the comparison point.
  922. .. templatefilter:: title
  923. title
  924. ~~~~~
  925. Converts a string into titlecase.
  926. .. templatefilter:: truncatewords
  927. truncatewords
  928. ~~~~~~~~~~~~~
  929. Truncates a string after a certain number of words.
  930. **Argument:** Number of words to truncate after
  931. For example::
  932. {{ value|truncatewords:2 }}
  933. If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel is ..."``.
  934. .. templatefilter:: truncatewords_html
  935. truncatewords_html
  936. ~~~~~~~~~~~~~~~~~~
  937. Similar to ``truncatewords``, except that it is aware of HTML tags. Any tags
  938. that are opened in the string and not closed before the truncation point, are
  939. closed immediately after the truncation.
  940. This is less efficient than ``truncatewords``, so should only be used when it
  941. is being passed HTML text.
  942. .. templatefilter:: unordered_list
  943. unordered_list
  944. ~~~~~~~~~~~~~~
  945. Recursively takes a self-nested list and returns an HTML unordered list --
  946. WITHOUT opening and closing <ul> tags.
  947. .. versionchanged:: 1.0
  948. The format accepted by ``unordered_list`` has changed to be easier to understand.
  949. The list is assumed to be in the proper format. For example, if ``var`` contains
  950. ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then
  951. ``{{ var|unordered_list }}`` would return::
  952. <li>States
  953. <ul>
  954. <li>Kansas
  955. <ul>
  956. <li>Lawrence</li>
  957. <li>Topeka</li>
  958. </ul>
  959. </li>
  960. <li>Illinois</li>
  961. </ul>
  962. </li>
  963. Note: the previous more restrictive and verbose format is still supported:
  964. ``['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]``,
  965. .. templatefilter:: upper
  966. upper
  967. ~~~~~
  968. Converts a string into all uppercase.
  969. For example::
  970. {{ value|upper }}
  971. If ``value`` is ``"Joel is a slug"``, the output will be ``"JOEL IS A SLUG"``.
  972. .. templatefilter:: urlencode
  973. urlencode
  974. ~~~~~~~~~
  975. Escapes a value for use in a URL.
  976. .. templatefilter:: urlize
  977. urlize
  978. ~~~~~~
  979. Converts URLs in plain text into clickable links.
  980. Note that if ``urlize`` is applied to text that already contains HTML markup,
  981. things won't work as expected. Apply this filter only to *plain* text.
  982. For example::
  983. {{ value|urlize }}
  984. If ``value`` is ``"Check out www.djangoproject.com"``, the output will be
  985. ``"Check out <a
  986. href="http://www.djangoproject.com">www.djangoproject.com</a>"``.
  987. .. templatefilter:: urlizetrunc
  988. urlizetrunc
  989. ~~~~~~~~~~~
  990. Converts URLs into clickable links, truncating URLs longer than the given
  991. character limit.
  992. As with urlize_, this filter should only be applied to *plain* text.
  993. **Argument:** Length to truncate URLs to
  994. For example::
  995. {{ value|urlizetrunc:15 }}
  996. If ``value`` is ``"Check out www.djangoproject.com"``, the output would be
  997. ``'Check out <a
  998. href="http://www.djangoproject.com">www.djangopr...</a>'``.
  999. .. templatefilter:: wordcount
  1000. wordcount
  1001. ~~~~~~~~~
  1002. Returns the number of words.
  1003. .. templatefilter:: wordwrap
  1004. wordwrap
  1005. ~~~~~~~~
  1006. Wraps words at specified line length.
  1007. **Argument:** number of characters at which to wrap the text
  1008. For example::
  1009. {{ value|wordwrap:5 }}
  1010. If ``value`` is ``Joel is a slug``, the output would be::
  1011. Joel
  1012. is a
  1013. slug
  1014. .. templatefilter:: yesno
  1015. yesno
  1016. ~~~~~
  1017. Given a string mapping values for true, false and (optionally) None,
  1018. returns one of those strings according to the value:
  1019. ========== ====================== ==================================
  1020. Value Argument Outputs
  1021. ========== ====================== ==================================
  1022. ``True`` ``"yeah,no,maybe"`` ``yeah``
  1023. ``False`` ``"yeah,no,maybe"`` ``no``
  1024. ``None`` ``"yeah,no,maybe"`` ``maybe``
  1025. ``None`` ``"yeah,no"`` ``"no"`` (converts None to False
  1026. if no mapping for None is given)
  1027. ========== ====================== ==================================
  1028. Other tags and filter libraries
  1029. ===============================
  1030. Django comes with a couple of other template-tag libraries that you have to
  1031. enable explicitly in your ``INSTALLED_APPS`` setting and enable in your
  1032. template with the ``{% load %}`` tag.
  1033. django.contrib.humanize
  1034. -----------------------
  1035. A set of Django template filters useful for adding a "human touch" to data. See
  1036. :ref:`ref-contrib-humanize`.
  1037. django.contrib.markup
  1038. ---------------------
  1039. A collection of template filters that implement these common markup languages:
  1040. * Textile
  1041. * Markdown
  1042. * ReST (ReStructured Text)
  1043. See :ref:`ref-contrib-markup`.
  1044. django.contrib.webdesign
  1045. ------------------------
  1046. A collection of template tags that can be useful while designing a website,
  1047. such as a generator of Lorem Ipsum text. See :ref:`ref-contrib-webdesign`.