PageRenderTime 22ms CodeModel.GetById 3ms app.highlight 7ms RepoModel.GetById 1ms app.codeStats 0ms

/docs/ref/templates/builtins.txt

https://code.google.com/p/mango-py/
Plain Text | 2281 lines | 1522 code | 759 blank | 0 comment | 0 complexity | 10700e293992cc83de86f42883c27609 MD5 | raw file
   1==================================
   2Built-in template tags and filters
   3==================================
   4
   5This document describes Django's built-in template tags and filters. It is
   6recommended that you use the :doc:`automatic documentation
   7</ref/contrib/admin/admindocs>`, if available, as this will also include
   8documentation for any custom tags or filters installed.
   9
  10.. _ref-templates-builtins-tags:
  11
  12Built-in tag reference
  13----------------------
  14
  15.. highlightlang:: html+django
  16
  17.. templatetag:: autoescape
  18
  19autoescape
  20~~~~~~~~~~
  21
  22Control the current auto-escaping behavior. This tag takes either ``on`` or
  23``off`` as an argument and that determines whether auto-escaping is in effect
  24inside the block. The block is closed with an ``endautoescape`` ending tag.
  25
  26When auto-escaping is in effect, all variable content has HTML escaping applied
  27to it before placing the result into the output (but after any filters have
  28been applied). This is equivalent to manually applying the ``escape`` filter
  29to each variable.
  30
  31The only exceptions are variables that are already marked as "safe" from
  32escaping, either by the code that populated the variable, or because it has had
  33the ``safe`` or ``escape`` filters applied.
  34
  35Sample usage::
  36
  37    {% autoescape on %}
  38        {{ body }}
  39    {% endautoescape %}
  40
  41.. templatetag:: block
  42
  43block
  44~~~~~
  45
  46Define a block that can be overridden by child templates. See
  47:ref:`Template inheritance <template-inheritance>` for more information.
  48
  49.. templatetag:: comment
  50
  51comment
  52~~~~~~~
  53
  54Ignore everything between ``{% comment %}`` and ``{% endcomment %}``
  55
  56.. templatetag:: csrf_token
  57
  58csrf_token
  59~~~~~~~~~~
  60
  61In the Django 1.1.X series, this is a no-op tag that returns an empty string for
  62future compatibility purposes.  In Django 1.2 and later, it is used for CSRF
  63protection, as described in the documentation for :doc:`Cross Site Request
  64Forgeries </ref/contrib/csrf>`.
  65
  66.. templatetag:: cycle
  67
  68cycle
  69~~~~~
  70
  71Cycle among the given strings or variables each time this tag is encountered.
  72
  73Within a loop, cycles among the given strings each time through the
  74loop::
  75
  76    {% for o in some_list %}
  77        <tr class="{% cycle 'row1' 'row2' %}">
  78            ...
  79        </tr>
  80    {% endfor %}
  81
  82You can use variables, too. For example, if you have two template variables,
  83``rowvalue1`` and ``rowvalue2``, you can cycle between their values like this::
  84
  85    {% for o in some_list %}
  86        <tr class="{% cycle rowvalue1 rowvalue2 %}">
  87            ...
  88        </tr>
  89    {% endfor %}
  90
  91Yes, you can mix variables and strings::
  92
  93    {% for o in some_list %}
  94        <tr class="{% cycle 'row1' rowvalue2 'row3' %}">
  95            ...
  96        </tr>
  97    {% endfor %}
  98
  99In some cases you might want to refer to the next value of a cycle from
 100outside of a loop. To do this, just give the ``{% cycle %}`` tag a name, using
 101"as", like this::
 102
 103    {% cycle 'row1' 'row2' as rowcolors %}
 104
 105From then on, you can insert the current value of the cycle wherever
 106you'd like in your template by referencing the cycle name as a context
 107variable. If you want to move the cycle onto the next value, you use
 108the cycle tag again, using the name of the variable. So, the following
 109template::
 110
 111    <tr>
 112        <td class="{% cycle 'row1' 'row2' as rowcolors %}">...</td>
 113        <td class="{{ rowcolors }}">...</td>
 114    </tr>
 115    <tr>
 116        <td class="{% cycle rowcolors %}">...</td>
 117        <td class="{{ rowcolors }}">...</td>
 118    </tr>
 119
 120would output::
 121
 122    <tr>
 123        <td class="row1">...</td>
 124        <td class="row1">...</td>
 125    </tr>
 126    <tr>
 127        <td class="row2">...</td>
 128        <td class="row2">...</td>
 129    </tr>
 130
 131You can use any number of values in a ``{% cycle %}`` tag, separated by spaces.
 132Values enclosed in single (``'``) or double quotes (``"``) are treated as
 133string literals, while values without quotes are treated as template variables.
 134
 135Note that the variables included in the cycle will not be escaped.
 136This is because template tags do not escape their content. Any HTML or
 137Javascript code contained in the printed variable will be rendered
 138as-is, which could potentially lead to security issues.
 139
 140If you need to escape the variables in the cycle, you must do so
 141explicitly::
 142
 143    {% filter force_escape %}
 144        {% cycle var1 var2 var3 %}
 145    {% endfilter %}
 146
 147For backwards compatibility, the ``{% cycle %}`` tag supports the much inferior
 148old syntax from previous Django versions. You shouldn't use this in any new
 149projects, but for the sake of the people who are still using it, here's what it
 150looks like::
 151
 152    {% cycle row1,row2,row3 %}
 153
 154In this syntax, each value gets interpreted as a literal string, and there's no
 155way to specify variable values. Or literal commas. Or spaces. Did we mention
 156you shouldn't use this syntax in any new projects?
 157
 158.. versionadded:: 1.3
 159
 160By default, when you use the ``as`` keyword with the cycle tag, the
 161usage of ``{% cycle %}`` that declares the cycle will itself output
 162the first value in the cycle. This could be a problem if you want to
 163use the value in a nested loop or an included template. If you want to
 164just declare the cycle, but not output the first value, you can add a
 165``silent`` keyword as the last keyword in the tag. For example::
 166
 167    {% for obj in some_list %}
 168        {% cycle 'row1' 'row2' as rowcolors silent %}
 169        <tr class="{{ rowcolors }}">{% include "subtemplate.html " %}</tr>
 170    {% endfor %}
 171
 172This will output a list of ``<tr>`` elements with ``class``
 173alternating between ``row1`` and ``row2``; the subtemplate will have
 174access to ``rowcolors`` in it's context that matches the class of the
 175``<tr>`` that encloses it. If the ``silent`` keyword were to be
 176omitted, ``row1`` would be emitted as normal text, outside the
 177``<tr>`` element.
 178
 179When the silent keyword is used on a cycle definition, the silence
 180automatically applies to all subsequent uses of the cycle tag. In,
 181the following template would output *nothing*, even though the second
 182call to ``{% cycle %}`` doesn't specify silent::
 183
 184    {% cycle 'row1' 'row2' as rowcolors silent %}
 185    {% cycle rowcolors %}
 186
 187.. templatetag:: debug
 188
 189debug
 190~~~~~
 191
 192Output a whole load of debugging information, including the current context and
 193imported modules.
 194
 195.. templatetag:: extends
 196
 197extends
 198~~~~~~~
 199
 200Signal that this template extends a parent template.
 201
 202This tag can be used in two ways:
 203
 204   * ``{% extends "base.html" %}`` (with quotes) uses the literal value
 205     ``"base.html"`` as the name of the parent template to extend.
 206
 207   * ``{% extends variable %}`` uses the value of ``variable``. If the variable
 208     evaluates to a string, Django will use that string as the name of the
 209     parent template. If the variable evaluates to a ``Template`` object,
 210     Django will use that object as the parent template.
 211
 212See :ref:`template-inheritance` for more information.
 213
 214.. templatetag:: filter
 215
 216filter
 217~~~~~~
 218
 219Filter the contents of the variable through variable filters.
 220
 221Filters can also be piped through each other, and they can have arguments --
 222just like in variable syntax.
 223
 224Sample usage::
 225
 226    {% filter force_escape|lower %}
 227        This text will be HTML-escaped, and will appear in all lowercase.
 228    {% endfilter %}
 229
 230.. templatetag:: firstof
 231
 232firstof
 233~~~~~~~
 234
 235Outputs the first variable passed that is not False, without escaping.
 236
 237Outputs nothing if all the passed variables are False.
 238
 239Sample usage::
 240
 241    {% firstof var1 var2 var3 %}
 242
 243This is equivalent to::
 244
 245    {% if var1 %}
 246        {{ var1|safe }}
 247    {% else %}{% if var2 %}
 248        {{ var2|safe }}
 249    {% else %}{% if var3 %}
 250        {{ var3|safe }}
 251    {% endif %}{% endif %}{% endif %}
 252
 253You can also use a literal string as a fallback value in case all
 254passed variables are False::
 255
 256    {% firstof var1 var2 var3 "fallback value" %}
 257
 258Note that the variables included in the firstof tag will not be
 259escaped. This is because template tags do not escape their content.
 260Any HTML or Javascript code contained in the printed variable will be
 261rendered as-is, which could potentially lead to security issues.
 262
 263If you need to escape the variables in the firstof tag, you must do so
 264explicitly::
 265
 266    {% filter force_escape %}
 267        {% firstof var1 var2 var3 "fallback value" %}
 268    {% endfilter %}
 269
 270.. templatetag:: for
 271
 272for
 273~~~
 274
 275Loop over each item in an array.  For example, to display a list of athletes
 276provided in ``athlete_list``::
 277
 278    <ul>
 279    {% for athlete in athlete_list %}
 280        <li>{{ athlete.name }}</li>
 281    {% endfor %}
 282    </ul>
 283
 284You can loop over a list in reverse by using ``{% for obj in list reversed %}``.
 285
 286If you need to loop over a list of lists, you can unpack the values
 287in each sub-list into individual variables. For example, if your context
 288contains a list of (x,y) coordinates called ``points``, you could use the
 289following to output the list of points::
 290
 291    {% for x, y in points %}
 292        There is a point at {{ x }},{{ y }}
 293    {% endfor %}
 294
 295This can also be useful if you need to access the items in a dictionary.
 296For example, if your context contained a dictionary ``data``, the following
 297would display the keys and values of the dictionary::
 298
 299    {% for key, value in data.items %}
 300        {{ key }}: {{ value }}
 301    {% endfor %}
 302
 303The for loop sets a number of variables available within the loop:
 304
 305    ==========================  ================================================
 306    Variable                    Description
 307    ==========================  ================================================
 308    ``forloop.counter``         The current iteration of the loop (1-indexed)
 309    ``forloop.counter0``        The current iteration of the loop (0-indexed)
 310    ``forloop.revcounter``      The number of iterations from the end of the
 311                                loop (1-indexed)
 312    ``forloop.revcounter0``     The number of iterations from the end of the
 313                                loop (0-indexed)
 314    ``forloop.first``           True if this is the first time through the loop
 315    ``forloop.last``            True if this is the last time through the loop
 316    ``forloop.parentloop``      For nested loops, this is the loop "above" the
 317                                current one
 318    ==========================  ================================================
 319
 320for ... empty
 321^^^^^^^^^^^^^
 322
 323The ``for`` tag can take an optional ``{% empty %}`` clause that will be
 324displayed if the given array is empty or could not be found::
 325
 326    <ul>
 327    {% for athlete in athlete_list %}
 328        <li>{{ athlete.name }}</li>
 329    {% empty %}
 330        <li>Sorry, no athlete in this list!</li>
 331    {% endfor %}
 332    <ul>
 333
 334The above is equivalent to -- but shorter, cleaner, and possibly faster
 335than -- the following::
 336
 337    <ul>
 338      {% if athlete_list %}
 339        {% for athlete in athlete_list %}
 340          <li>{{ athlete.name }}</li>
 341        {% endfor %}
 342      {% else %}
 343        <li>Sorry, no athletes in this list.</li>
 344      {% endif %}
 345    </ul>
 346
 347.. templatetag:: if
 348
 349if
 350~~
 351
 352The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e.
 353exists, is not empty, and is not a false boolean value) the contents of the
 354block are output::
 355
 356    {% if athlete_list %}
 357        Number of athletes: {{ athlete_list|length }}
 358    {% else %}
 359        No athletes.
 360    {% endif %}
 361
 362In the above, if ``athlete_list`` is not empty, the number of athletes will be
 363displayed by the ``{{ athlete_list|length }}`` variable.
 364
 365As you can see, the ``if`` tag can take an optional ``{% else %}`` clause that
 366will be displayed if the test fails.
 367
 368Boolean operators
 369^^^^^^^^^^^^^^^^^
 370
 371``if`` tags may use ``and``, ``or`` or ``not`` to test a number of variables or
 372to negate a given variable::
 373
 374    {% if athlete_list and coach_list %}
 375        Both athletes and coaches are available.
 376    {% endif %}
 377
 378    {% if not athlete_list %}
 379        There are no athletes.
 380    {% endif %}
 381
 382    {% if athlete_list or coach_list %}
 383        There are some athletes or some coaches.
 384    {% endif %}
 385
 386    {% if not athlete_list or coach_list %}
 387        There are no athletes or there are some coaches (OK, so
 388        writing English translations of boolean logic sounds
 389        stupid; it's not our fault).
 390    {% endif %}
 391
 392    {% if athlete_list and not coach_list %}
 393        There are some athletes and absolutely no coaches.
 394    {% endif %}
 395
 396.. versionchanged:: 1.2
 397
 398Use of both ``and`` and ``or`` clauses within the same tag is allowed, with
 399``and`` having higher precedence than ``or`` e.g.::
 400
 401    {% if athlete_list and coach_list or cheerleader_list %}
 402
 403will be interpreted like:
 404
 405.. code-block:: python
 406
 407    if (athlete_list and coach_list) or cheerleader_list
 408
 409Use of actual brackets in the ``if`` tag is invalid syntax.  If you need them to
 410indicate precedence, you should use nested ``if`` tags.
 411
 412.. versionadded:: 1.2
 413
 414
 415``if`` tags may also use the operators ``==``, ``!=``, ``<``, ``>``,
 416``<=``, ``>=`` and ``in`` which work as follows:
 417
 418
 419``==`` operator
 420^^^^^^^^^^^^^^^
 421
 422Equality. Example::
 423
 424    {% if somevar == "x" %}
 425      This appears if variable somevar equals the string "x"
 426    {% endif %}
 427
 428``!=`` operator
 429^^^^^^^^^^^^^^^
 430
 431Inequality. Example::
 432
 433    {% if somevar != "x" %}
 434      This appears if variable somevar does not equal the string "x",
 435      or if somevar is not found in the context
 436    {% endif %}
 437
 438``<`` operator
 439^^^^^^^^^^^^^^
 440
 441Less than. Example::
 442
 443    {% if somevar < 100 %}
 444      This appears if variable somevar is less than 100.
 445    {% endif %}
 446
 447``>`` operator
 448^^^^^^^^^^^^^^
 449
 450Greater than. Example::
 451
 452    {% if somevar > 0 %}
 453      This appears if variable somevar is greater than 0.
 454    {% endif %}
 455
 456``<=`` operator
 457^^^^^^^^^^^^^^^
 458
 459Less than or equal to. Example::
 460
 461    {% if somevar <= 100 %}
 462      This appears if variable somevar is less than 100 or equal to 100.
 463    {% endif %}
 464
 465``>=`` operator
 466^^^^^^^^^^^^^^^
 467
 468Greater than or equal to. Example::
 469
 470    {% if somevar >= 1 %}
 471      This appears if variable somevar is greater than 1 or equal to 1.
 472    {% endif %}
 473
 474``in`` operator
 475^^^^^^^^^^^^^^^
 476
 477Contained within. This operator is supported by many Python containers to test
 478whether the given value is in the container.  The following are some examples of
 479how ``x in y`` will be interpreted::
 480
 481    {% if "bc" in "abcdef" %}
 482      This appears since "bc" is a substring of "abcdef"
 483    {% endif %}
 484
 485    {% if "hello" in greetings %}
 486      If greetings is a list or set, one element of which is the string
 487      "hello", this will appear.
 488    {% endif %}
 489
 490    {% if user in users %}
 491      If users is a QuerySet, this will appear if user is an
 492      instance that belongs to the QuerySet.
 493    {% endif %}
 494
 495``not in`` operator
 496~~~~~~~~~~~~~~~~~~~~
 497
 498Not contained within.  This is the negation of the ``in`` operator.
 499
 500
 501The comparison operators cannot be 'chained' like in Python or in mathematical
 502notation. For example, instead of using::
 503
 504    {% if a > b > c %}  (WRONG)
 505
 506you should use::
 507
 508    {% if a > b and b > c %}
 509
 510
 511Filters
 512^^^^^^^
 513
 514You can also use filters in the ``if`` expression. For example::
 515
 516    {% if messages|length >= 100 %}
 517       You have lots of messages today!
 518    {% endif %}
 519
 520Complex expressions
 521^^^^^^^^^^^^^^^^^^^
 522
 523All of the above can be combined to form complex expressions. For such
 524expressions, it can be important to know how the operators are grouped when the
 525expression is evaluated - that is, the precedence rules.  The precedence of the
 526operators, from lowest to highest, is as follows:
 527
 528 * ``or``
 529 * ``and``
 530 * ``not``
 531 * ``in``
 532 * ``==``, ``!=``, ``<``, ``>``,``<=``, ``>=``
 533
 534(This follows Python exactly). So, for example, the following complex if tag:
 535
 536.. code-block:: django
 537
 538    {% if a == b or c == d and e %}
 539
 540...will be interpreted as:
 541
 542.. code-block:: python
 543
 544    (a == b) or ((c == d) and e)
 545
 546If you need different precedence, you will need to use nested if tags. Sometimes
 547that is better for clarity anyway, for the sake of those who do not know the
 548precedence rules.
 549
 550
 551.. templatetag:: ifchanged
 552
 553ifchanged
 554~~~~~~~~~
 555
 556Check if a value has changed from the last iteration of a loop.
 557
 558The 'ifchanged' block tag is used within a loop. It has two possible uses.
 559
 5601. Checks its own rendered contents against its previous state and only
 561   displays the content if it has changed. For example, this displays a list of
 562   days, only displaying the month if it changes::
 563
 564        <h1>Archive for {{ year }}</h1>
 565
 566        {% for date in days %}
 567            {% ifchanged %}<h3>{{ date|date:"F" }}</h3>{% endifchanged %}
 568            <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
 569        {% endfor %}
 570
 5712. If given a variable, check whether that variable has changed. For
 572   example, the following shows the date every time it changes, but
 573   only shows the hour if both the hour and the date has changed::
 574
 575        {% for date in days %}
 576            {% ifchanged date.date %} {{ date.date }} {% endifchanged %}
 577            {% ifchanged date.hour date.date %}
 578                {{ date.hour }}
 579            {% endifchanged %}
 580        {% endfor %}
 581
 582The ``ifchanged`` tag can also take an optional ``{% else %}`` clause that
 583will be displayed if the value has not changed::
 584
 585        {% for match in matches %}
 586            <div style="background-color:
 587                {% ifchanged match.ballot_id %}
 588                    {% cycle "red" "blue" %}
 589                {% else %}
 590                    grey
 591                {% endifchanged %}
 592            ">{{ match }}</div>
 593        {% endfor %}
 594
 595.. templatetag:: ifequal
 596
 597ifequal
 598~~~~~~~
 599
 600Output the contents of the block if the two arguments equal each other.
 601
 602Example::
 603
 604    {% ifequal user.id comment.user_id %}
 605        ...
 606    {% endifequal %}
 607
 608As in the ``{% if %}`` tag, an ``{% else %}`` clause is optional.
 609
 610The arguments can be hard-coded strings, so the following is valid::
 611
 612    {% ifequal user.username "adrian" %}
 613        ...
 614    {% endifequal %}
 615
 616It is only possible to compare an argument to template variables or strings.
 617You cannot check for equality with Python objects such as ``True`` or
 618``False``.  If you need to test if something is true or false, use the ``if``
 619tag instead.
 620
 621.. versionadded:: 1.2
 622   An alternative to the ``ifequal`` tag is to use the :ttag:`if` tag and the ``==`` operator.
 623
 624.. templatetag:: ifnotequal
 625
 626ifnotequal
 627~~~~~~~~~~
 628
 629Just like ``ifequal``, except it tests that the two arguments are not equal.
 630
 631.. versionadded:: 1.2
 632   An alternative to the ``ifnotequal`` tag is to use the :ttag:`if` tag and the ``!=`` operator.
 633
 634.. templatetag:: include
 635
 636include
 637~~~~~~~
 638
 639Loads a template and renders it with the current context. This is a way of
 640"including" other templates within a template.
 641
 642The template name can either be a variable or a hard-coded (quoted) string,
 643in either single or double quotes.
 644
 645This example includes the contents of the template ``"foo/bar.html"``::
 646
 647    {% include "foo/bar.html" %}
 648
 649This example includes the contents of the template whose name is contained in
 650the variable ``template_name``::
 651
 652    {% include template_name %}
 653
 654An included template is rendered with the context of the template that's
 655including it. This example produces the output ``"Hello, John"``:
 656
 657    * Context: variable ``person`` is set to ``"john"``.
 658    * Template::
 659
 660        {% include "name_snippet.html" %}
 661
 662    * The ``name_snippet.html`` template::
 663
 664        {{ greeting }}, {{ person|default:"friend" }}!
 665
 666.. versionchanged:: 1.3
 667   Additional context and exclusive context.
 668
 669You can pass additional context to the template using keyword arguments::
 670
 671    {% include "name_snippet.html" with person="Jane" greeting="Hello" %}
 672
 673If you want to only render the context with the variables provided (or even
 674no variables at all), use the ``only`` option::
 675
 676    {% include "name_snippet.html" with greeting="Hi" only %}
 677
 678.. note::
 679    The :ttag:`include` tag should be considered as an implementation of
 680    "render this subtemplate and include the HTML", not as "parse this
 681    subtemplate and include its contents as if it were part of the parent".
 682    This means that there is no shared state between included templates --
 683    each include is a completely independent rendering process.
 684
 685See also: ``{% ssi %}``.
 686
 687.. templatetag:: load
 688
 689load
 690~~~~
 691
 692Load a custom template tag set.
 693
 694For example, the following template would load all the tags and filters
 695registered in ``somelibrary`` and ``otherlibrary``::
 696
 697    {% load somelibrary otherlibrary %}
 698
 699.. versionchanged:: 1.3
 700
 701You can also selectively load individual filters or tags from a library, using
 702the ``from`` argument. In this example, the template tags/filters named ``foo``
 703and ``bar`` will be loaded from ``somelibrary``::
 704
 705    {% load foo bar from somelibrary %}
 706
 707See :doc:`Custom tag and filter libraries </howto/custom-template-tags>` for
 708more information.
 709
 710.. templatetag:: now
 711
 712now
 713~~~
 714
 715Display the current date and/or time, using a format according to the given
 716string. Such string can contain format specifiers characters as described
 717in the :tfilter:`date` filter section.
 718
 719Example::
 720
 721    It is {% now "jS F Y H:i" %}
 722
 723Note that you can backslash-escape a format string if you want to use the
 724"raw" value. In this example, "f" is backslash-escaped, because otherwise
 725"f" is a format string that displays the time. The "o" doesn't need to be
 726escaped, because it's not a format character::
 727
 728    It is the {% now "jS o\f F" %}
 729
 730This would display as "It is the 4th of September".
 731
 732.. templatetag:: regroup
 733
 734regroup
 735~~~~~~~
 736
 737Regroup a list of alike objects by a common attribute.
 738
 739This complex tag is best illustrated by use of an example: say that ``people``
 740is a list of people represented by dictionaries with ``first_name``,
 741``last_name``, and ``gender`` keys:
 742
 743.. code-block:: python
 744
 745    people = [
 746        {'first_name': 'George', 'last_name': 'Bush', 'gender': 'Male'},
 747        {'first_name': 'Bill', 'last_name': 'Clinton', 'gender': 'Male'},
 748        {'first_name': 'Margaret', 'last_name': 'Thatcher', 'gender': 'Female'},
 749        {'first_name': 'Condoleezza', 'last_name': 'Rice', 'gender': 'Female'},
 750        {'first_name': 'Pat', 'last_name': 'Smith', 'gender': 'Unknown'},
 751    ]
 752
 753...and you'd like to display a hierarchical list that is ordered by gender,
 754like this:
 755
 756    * Male:
 757        * George Bush
 758        * Bill Clinton
 759    * Female:
 760        * Margaret Thatcher
 761        * Condoleezza Rice
 762    * Unknown:
 763        * Pat Smith
 764
 765You can use the ``{% regroup %}`` tag to group the list of people by gender.
 766The following snippet of template code would accomplish this::
 767
 768    {% regroup people by gender as gender_list %}
 769
 770    <ul>
 771    {% for gender in gender_list %}
 772        <li>{{ gender.grouper }}
 773        <ul>
 774            {% for item in gender.list %}
 775            <li>{{ item.first_name }} {{ item.last_name }}</li>
 776            {% endfor %}
 777        </ul>
 778        </li>
 779    {% endfor %}
 780    </ul>
 781
 782Let's walk through this example. ``{% regroup %}`` takes three arguments: the
 783list you want to regroup, the attribute to group by, and the name of the
 784resulting list. Here, we're regrouping the ``people`` list by the ``gender``
 785attribute and calling the result ``gender_list``.
 786
 787``{% regroup %}`` produces a list (in this case, ``gender_list``) of
 788**group objects**. Each group object has two attributes:
 789
 790    * ``grouper`` -- the item that was grouped by (e.g., the string "Male" or
 791      "Female").
 792    * ``list`` -- a list of all items in this group (e.g., a list of all people
 793      with gender='Male').
 794
 795Note that ``{% regroup %}`` does not order its input! Our example relies on
 796the fact that the ``people`` list was ordered by ``gender`` in the first place.
 797If the ``people`` list did *not* order its members by ``gender``, the regrouping
 798would naively display more than one group for a single gender. For example,
 799say the ``people`` list was set to this (note that the males are not grouped
 800together):
 801
 802.. code-block:: python
 803
 804    people = [
 805        {'first_name': 'Bill', 'last_name': 'Clinton', 'gender': 'Male'},
 806        {'first_name': 'Pat', 'last_name': 'Smith', 'gender': 'Unknown'},
 807        {'first_name': 'Margaret', 'last_name': 'Thatcher', 'gender': 'Female'},
 808        {'first_name': 'George', 'last_name': 'Bush', 'gender': 'Male'},
 809        {'first_name': 'Condoleezza', 'last_name': 'Rice', 'gender': 'Female'},
 810    ]
 811
 812With this input for ``people``, the example ``{% regroup %}`` template code
 813above would result in the following output:
 814
 815    * Male:
 816        * Bill Clinton
 817    * Unknown:
 818        * Pat Smith
 819    * Female:
 820        * Margaret Thatcher
 821    * Male:
 822        * George Bush
 823    * Female:
 824        * Condoleezza Rice
 825
 826The easiest solution to this gotcha is to make sure in your view code that the
 827data is ordered according to how you want to display it.
 828
 829Another solution is to sort the data in the template using the ``dictsort``
 830filter, if your data is in a list of dictionaries::
 831
 832    {% regroup people|dictsort:"gender" by gender as gender_list %}
 833
 834
 835Grouping on other properties
 836^^^^^^^^^^^^^^^^^^^^^^^^^^^^
 837
 838Any valid template lookup is a legal grouping attribute for the regroup
 839tag, including methods, attributes, dictionary keys and list items. For
 840example, if the "gender" field is a foreign key to a class with
 841an attribute "description," you could use::
 842
 843    {% regroup people by gender.description as gender_list %}
 844
 845Or, if ``gender`` is a field with ``choices``, it will have a
 846:meth:`~django.db.models.Model.get_FOO_display` method available as an
 847attribute, allowing  you to group on the display string rather than the
 848``choices`` key::
 849
 850    {% regroup people by get_gender_display as gender_list %}
 851
 852``{{ gender.grouper }}`` will now display the value fields from the
 853``choices`` set rather than the keys.
 854
 855.. templatetag:: spaceless
 856
 857spaceless
 858~~~~~~~~~
 859
 860Removes whitespace between HTML tags. This includes tab
 861characters and newlines.
 862
 863Example usage::
 864
 865    {% spaceless %}
 866        <p>
 867            <a href="foo/">Foo</a>
 868        </p>
 869    {% endspaceless %}
 870
 871This example would return this HTML::
 872
 873    <p><a href="foo/">Foo</a></p>
 874
 875Only space between *tags* is removed -- not space between tags and text. In
 876this example, the space around ``Hello`` won't be stripped::
 877
 878    {% spaceless %}
 879        <strong>
 880            Hello
 881        </strong>
 882    {% endspaceless %}
 883
 884.. templatetag:: ssi
 885
 886ssi
 887~~~
 888
 889Output the contents of a given file into the page.
 890
 891Like a simple "include" tag, ``{% ssi %}`` includes the contents of another
 892file -- which must be specified using an absolute path -- in the current
 893page::
 894
 895    {% ssi /home/html/ljworld.com/includes/right_generic.html %}
 896
 897If the optional "parsed" parameter is given, the contents of the included
 898file are evaluated as template code, within the current context::
 899
 900    {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %}
 901
 902Note that if you use ``{% ssi %}``, you'll need to define
 903:setting:`ALLOWED_INCLUDE_ROOTS` in your Django settings, as a security measure.
 904
 905See also: ``{% include %}``.
 906
 907.. admonition:: Forwards compatibility
 908
 909    .. versionchanged:: 1.3
 910
 911    In Django 1.5, the behavior of the :ttag:`ssi` template tag will
 912    change, with the first argument being made into a context
 913    variable, rather than being a special case unquoted constant. This
 914    will allow the :ttag:`ssi` tag to use a context variable as the
 915    value of the page to be included.
 916
 917    In order to provide a forwards compatibility path, Django 1.3
 918    provides a future compatibility library -- ``future`` -- that
 919    implements the new behavior. To use this library, add a
 920    :ttag:`load` call at the top of any template using the :ttag:`ssi`
 921    tag, and wrap the first argument to the :ttag:`ssi` tag in quotes.
 922    For example::
 923
 924        {% load ssi from future %}
 925        {% ssi '/home/html/ljworld.com/includes/right_generic.html' %}
 926
 927    In Django 1.5, the unquoted constant behavior will be replaced
 928    with the behavior provided by the ``future`` tag library.
 929    Existing templates should be migrated to use the new syntax.
 930
 931.. templatetag:: templatetag
 932
 933templatetag
 934~~~~~~~~~~~
 935
 936Output one of the syntax characters used to compose template tags.
 937
 938Since the template system has no concept of "escaping", to display one of the
 939bits used in template tags, you must use the ``{% templatetag %}`` tag.
 940
 941The argument tells which template bit to output:
 942
 943    ==================  =======
 944    Argument            Outputs
 945    ==================  =======
 946    ``openblock``       ``{%``
 947    ``closeblock``      ``%}``
 948    ``openvariable``    ``{{``
 949    ``closevariable``   ``}}``
 950    ``openbrace``       ``{``
 951    ``closebrace``      ``}``
 952    ``opencomment``     ``{#``
 953    ``closecomment``    ``#}``
 954    ==================  =======
 955
 956.. templatetag:: url
 957
 958url
 959~~~
 960
 961Returns an absolute path reference (a URL without the domain name) matching a
 962given view function and optional parameters. This is a way to output links
 963without violating the DRY principle by having to hard-code URLs in your
 964templates::
 965
 966    {% url path.to.some_view v1 v2 %}
 967
 968The first argument is a path to a view function in the format
 969``package.package.module.function``. Additional arguments are optional and
 970should be space-separated values that will be used as arguments in the URL.
 971The example above shows passing positional arguments. Alternatively you may
 972use keyword syntax::
 973
 974    {% url path.to.some_view arg1=v1 arg2=v2 %}
 975
 976Do not mix both positional and keyword syntax in a single call. All arguments
 977required by the URLconf should be present.
 978
 979For example, suppose you have a view, ``app_views.client``, whose URLconf
 980takes a client ID (here, ``client()`` is a method inside the views file
 981``app_views.py``). The URLconf line might look like this:
 982
 983.. code-block:: python
 984
 985    ('^client/(\d+)/$', 'app_views.client')
 986
 987If this app's URLconf is included into the project's URLconf under a path
 988such as this:
 989
 990.. code-block:: python
 991
 992    ('^clients/', include('project_name.app_name.urls'))
 993
 994...then, in a template, you can create a link to this view like this::
 995
 996    {% url app_views.client client.id %}
 997
 998The template tag will output the string ``/clients/client/123/``.
 999
1000If you're using :ref:`named URL patterns <naming-url-patterns>`, you can
1001refer to the name of the pattern in the ``url`` tag instead of using the
1002path to the view.
1003
1004Note that if the URL you're reversing doesn't exist, you'll get an
1005:exc:`~django.core.urlresolvers.NoReverseMatch` exception raised, which will
1006cause your site to display an error page.
1007
1008If you'd like to retrieve a URL without displaying it, you can use a slightly
1009different call::
1010
1011
1012    {% url path.to.view arg arg2 as the_url %}
1013
1014    <a href="{{ the_url }}">I'm linking to {{ the_url }}</a>
1015
1016This ``{% url ... as var %}`` syntax will *not* cause an error if the view is
1017missing. In practice you'll use this to link to views that are optional::
1018
1019    {% url path.to.view as the_url %}
1020    {% if the_url %}
1021      <a href="{{ the_url }}">Link to optional stuff</a>
1022    {% endif %}
1023
1024If you'd like to retrieve a namespaced URL, specify the fully qualified name::
1025
1026    {% url myapp:view-name %}
1027
1028This will follow the normal :ref:`namespaced URL resolution strategy
1029<topics-http-reversing-url-namespaces>`, including using any hints provided
1030by the context as to the current application.
1031
1032.. versionchanged:: 1.2
1033
1034For backwards compatibility, the ``{% url %}`` tag also supports the
1035use of commas to separate arguments. You shouldn't use this in any new
1036projects, but for the sake of the people who are still using it,
1037here's what it looks like::
1038
1039    {% url path.to.view arg,arg2 %}
1040    {% url path.to.view arg, arg2 %}
1041
1042This syntax doesn't support the use of literal commas, or equals
1043signs. Did we mention you shouldn't use this syntax in any new
1044projects?
1045
1046.. admonition:: Forwards compatibility
1047
1048    .. versionchanged:: 1.3
1049
1050    In Django 1.5, the behavior of the :ttag:`url` template tag will
1051    change, with the first argument being made into a context
1052    variable, rather than being a special case unquoted constant. This
1053    will allow the :ttag:`url` tag to use a context variable as the
1054    value of the URL name to be reversed.
1055
1056    In order to provide a forwards compatibility path, Django 1.3
1057    provides a future compatibility library -- ``future`` -- that
1058    implements the new behavior. To use this library, add a
1059    :ttag:`load` call at the top of any template using the :ttag:`url`
1060    tag, and wrap the first argument to the :ttag:`url` tag in quotes.
1061    For example::
1062
1063        {% load url from future %}
1064        {% url 'myapp:view-name' %}
1065
1066    The new library also drops support for the comma syntax for
1067    separating arguments to the :ttag:`url` template tag.
1068
1069    In Django 1.5, the old behavior will be replaced with the behavior
1070    provided by the ``future`` tag library. Existing templates be
1071    migrated to use the new syntax.
1072
1073.. templatetag:: widthratio
1074
1075widthratio
1076~~~~~~~~~~
1077
1078For creating bar charts and such, this tag calculates the ratio of a given value
1079to a maximum value, and then applies that ratio to a constant.
1080
1081For example::
1082
1083    <img src="bar.gif" height="10" width="{% widthratio this_value max_value 100 %}" />
1084
1085Above, if ``this_value`` is 175 and ``max_value`` is 200, the image in the
1086above example will be 88 pixels wide (because 175/200 = .875; .875 * 100 = 87.5
1087which is rounded up to 88).
1088
1089.. templatetag:: with
1090
1091with
1092~~~~
1093
1094.. versionchanged:: 1.3
1095   New keyword argument format and multiple variable assignments.
1096
1097Caches a complex variable under a simpler name. This is useful when accessing
1098an "expensive" method (e.g., one that hits the database) multiple times.
1099
1100For example::
1101
1102    {% with total=business.employees.count %}
1103        {{ total }} employee{{ total|pluralize }}
1104    {% endwith %}
1105
1106The populated variable (in the example above, ``total``) is only available
1107between the ``{% with %}`` and ``{% endwith %}`` tags.
1108
1109You can assign more than one context variable::
1110
1111    {% with alpha=1 beta=2 %}
1112        ...
1113    {% endwith %}
1114
1115.. note:: The previous more verbose format is still supported:
1116   ``{% with business.employees.count as total %}``
1117
1118.. _ref-templates-builtins-filters:
1119
1120Built-in filter reference
1121-------------------------
1122
1123.. templatefilter:: add
1124
1125add
1126~~~
1127
1128Adds the argument to the value.
1129
1130For example::
1131
1132    {{ value|add:"2" }}
1133
1134If ``value`` is ``4``, then the output will be ``6``.
1135
1136.. versionchanged:: 1.2
1137   The following behavior didn't exist in previous Django versions.
1138
1139This filter will first try to coerce both values to integers. If this fails,
1140it'll attempt to add the values together anyway. This will work on some data
1141types (strings, list, etc.) and fail on others. If it fails, the result will
1142be an empty string.
1143
1144For example, if we have::
1145
1146    {{ first|add:second }}
1147
1148and ``first`` is ``[1, 2, 3]`` and ``second`` is ``[4, 5, 6]``, then the
1149output will be ``[1, 2, 3, 4, 5, 6]``.
1150
1151.. warning::
1152
1153    Strings that can be coerced to integers will be **summed**, not
1154    concatenated, as in the first example above.
1155
1156.. templatefilter:: addslashes
1157
1158addslashes
1159~~~~~~~~~~
1160
1161Adds slashes before quotes. Useful for escaping strings in CSV, for example.
1162
1163For example::
1164
1165    {{ value|addslashes }}
1166
1167If ``value`` is ``"I'm using Django"``, the output will be ``"I\'m using Django"``.
1168
1169.. templatefilter:: capfirst
1170
1171capfirst
1172~~~~~~~~
1173
1174Capitalizes the first character of the value.
1175
1176For example::
1177
1178    {{ value|capfirst }}
1179
1180If ``value`` is ``"django"``, the output will be ``"Django"``.
1181
1182.. templatefilter:: center
1183
1184center
1185~~~~~~
1186
1187Centers the value in a field of a given width.
1188
1189For example::
1190
1191    "{{ value|center:"15" }}"
1192
1193If ``value`` is ``"Django"``, the output will be ``"     Django    "``.
1194
1195.. templatefilter:: cut
1196
1197cut
1198~~~
1199
1200Removes all values of arg from the given string.
1201
1202For example::
1203
1204    {{ value|cut:" "}}
1205
1206If ``value`` is ``"String with spaces"``, the output will be ``"Stringwithspaces"``.
1207
1208.. templatefilter:: date
1209
1210date
1211~~~~
1212
1213Formats a date according to the given format.
1214
1215Uses the same format as PHP's ``date()`` function (http://php.net/date)
1216with some custom extensions.
1217
1218Available format strings:
1219
1220    ================  ========================================  =====================
1221    Format character  Description                               Example output
1222    ================  ========================================  =====================
1223    a                 ``'a.m.'`` or ``'p.m.'`` (Note that       ``'a.m.'``
1224                      this is slightly different than PHP's
1225                      output, because this includes periods
1226                      to match Associated Press style.)
1227    A                 ``'AM'`` or ``'PM'``.                     ``'AM'``
1228    b                 Month, textual, 3 letters, lowercase.     ``'jan'``
1229    B                 Not implemented.
1230    c                 ISO 8601 Format.                          ``2008-01-02T10:30:00.000123``
1231    d                 Day of the month, 2 digits with           ``'01'`` to ``'31'``
1232                      leading zeros.
1233    D                 Day of the week, textual, 3 letters.      ``'Fri'``
1234    E                 Month, locale specific alternative
1235                      representation usually used for long
1236                      date representation.                      ``'listopada'`` (for Polish locale, as opposed to ``'Listopad'``)
1237    f                 Time, in 12-hour hours and minutes,       ``'1'``, ``'1:30'``
1238                      with minutes left off if they're zero.
1239                      Proprietary extension.
1240    F                 Month, textual, long.                     ``'January'``
1241    g                 Hour, 12-hour format without leading      ``'1'`` to ``'12'``
1242                      zeros.
1243    G                 Hour, 24-hour format without leading      ``'0'`` to ``'23'``
1244                      zeros.
1245    h                 Hour, 12-hour format.                     ``'01'`` to ``'12'``
1246    H                 Hour, 24-hour format.                     ``'00'`` to ``'23'``
1247    i                 Minutes.                                  ``'00'`` to ``'59'``
1248    I                 Not implemented.
1249    j                 Day of the month without leading          ``'1'`` to ``'31'``
1250                      zeros.
1251    l                 Day of the week, textual, long.           ``'Friday'``
1252    L                 Boolean for whether it's a leap year.     ``True`` or ``False``
1253    m                 Month, 2 digits with leading zeros.       ``'01'`` to ``'12'``
1254    M                 Month, textual, 3 letters.                ``'Jan'``
1255    n                 Month without leading zeros.              ``'1'`` to ``'12'``
1256    N                 Month abbreviation in Associated Press    ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'``
1257                      style. Proprietary extension.
1258    O                 Difference to Greenwich time in hours.    ``'+0200'``
1259    P                 Time, in 12-hour hours, minutes and       ``'1 a.m.'``, ``'1:30 p.m.'``, ``'midnight'``, ``'noon'``, ``'12:30 p.m.'``
1260                      'a.m.'/'p.m.', with minutes left off
1261                      if they're zero and the special-case
1262                      strings 'midnight' and 'noon' if
1263                      appropriate. Proprietary extension.
1264    r                 RFC 2822 formatted date.                  ``'Thu, 21 Dec 2000 16:01:07 +0200'``
1265    s                 Seconds, 2 digits with leading zeros.     ``'00'`` to ``'59'``
1266    S                 English ordinal suffix for day of the     ``'st'``, ``'nd'``, ``'rd'`` or ``'th'``
1267                      month, 2 characters.
1268    t                 Number of days in the given month.        ``28`` to ``31``
1269    T                 Time zone of this machine.                ``'EST'``, ``'MDT'``
1270    u                 Microseconds.                             ``0`` to ``999999``
1271    U                 Seconds since the Unix Epoch
1272                      (January 1 1970 00:00:00 UTC).
1273    w                 Day of the week, digits without           ``'0'`` (Sunday) to ``'6'`` (Saturday)
1274                      leading zeros.
1275    W                 ISO-8601 week number of year, with        ``1``, ``53``
1276                      weeks starting on Monday.
1277    y                 Year, 2 digits.                           ``'99'``
1278    Y                 Year, 4 digits.                           ``'1999'``
1279    z                 Day of the year.                          ``0`` to ``365``
1280    Z                 Time zone offset in seconds. The          ``-43200`` to ``43200``
1281                      offset for timezones west of UTC is
1282                      always negative, and for those east of
1283                      UTC is always positive.
1284    ================  ========================================  =====================
1285
1286.. versionadded:: 1.2
1287
1288The ``c`` and ``u`` format specification characters were added in Django 1.2.
1289
1290For example::
1291
1292    {{ value|date:"D d M Y" }}
1293
1294If ``value`` is a ``datetime`` object (e.g., the result of
1295``datetime.datetime.now()``), the output will be the string
1296``'Wed 09 Jan 2008'``.
1297
1298The format passed can be one of the predefined ones :setting:`DATE_FORMAT`,
1299:setting:`DATETIME_FORMAT`, :setting:`SHORT_DATE_FORMAT` or
1300:setting:`SHORT_DATETIME_FORMAT`, or a custom format that uses the format
1301specifiers shown in the table above. Note that predefined formats may vary
1302depending on the current locale.
1303
1304Assuming that :setting:`USE_L10N` is ``True`` and :setting:`LANGUAGE_CODE` is,
1305for example, ``"es"``, then for::
1306
1307    {{ value|date:"SHORT_DATE_FORMAT" }}
1308
1309the output would be the string ``"09/01/2008"`` (the ``"SHORT_DATE_FORMAT"``
1310format specifier for the ``es`` locale as shipped with Django is ``"d/m/Y"``).
1311
1312When used without a format string::
1313
1314    {{ value|date }}
1315
1316...the formatting string defined in the :setting:`DATE_FORMAT` setting will be
1317used, without applying any localization.
1318
1319.. versionchanged:: 1.2
1320    Predefined formats can now be influenced by the current locale.
1321
1322.. templatefilter:: default
1323
1324default
1325~~~~~~~
1326
1327If value evaluates to ``False``, use given default. Otherwise, use the value.
1328
1329For example::
1330
1331    {{ value|default:"nothing" }}
1332
1333If ``value`` is ``""`` (the empty string), the output will be ``nothing``.
1334
1335.. templatefilter:: default_if_none
1336
1337default_if_none
1338~~~~~~~~~~~~~~~
1339
1340If (and only if) value is ``None``, use given default. Otherwise, use the
1341value.
1342
1343Note that if an empty string is given, the default value will *not* be used.
1344Use the ``default`` filter if you want to fallback for empty strings.
1345
1346For example::
1347
1348    {{ value|default_if_none:"nothing" }}
1349
1350If ``value`` is ``None``, the output will be the string ``"nothing"``.
1351
1352.. templatefilter:: dictsort
1353
1354dictsort
1355~~~~~~~~
1356
1357Takes a list of dictionaries and returns that list sorted by the key given in
1358the argument.
1359
1360For example::
1361
1362    {{ value|dictsort:"name" }}
1363
1364If ``value`` is:
1365
1366.. code-block:: python
1367
1368    [
1369        {'name': 'zed', 'age': 19},
1370        {'name': 'amy', 'age': 22},
1371        {'name': 'joe', 'age': 31},
1372    ]
1373
1374then the output would be:
1375
1376.. code-block:: python
1377
1378    [
1379        {'name': 'amy', 'age': 22},
1380        {'name': 'joe', 'age': 31},
1381        {'name': 'zed', 'age': 19},
1382    ]
1383
1384.. templatefilter:: dictsortreversed
1385
1386dictsortreversed
1387~~~~~~~~~~~~~~~~
1388
1389Takes a list of dictionaries and returns that list sorted in reverse order by
1390the key given in the argument. This works exactly the same as the above filter,
1391but the returned value will be in reverse order.
1392
1393.. templatefilter:: divisibleby
1394
1395divisibleby
1396~~~~~~~~~~~
1397
1398Returns ``True`` if the value is divisible by the argument.
1399
1400For example::
1401
1402    {{ value|divisibleby:"3" }}
1403
1404If ``value`` is ``21``, the output would be ``True``.
1405
1406.. templatefilter:: escape
1407
1408escape
1409~~~~~~
1410
1411Escapes a string's HTML. Specifically, it makes these replacements:
1412
1413    * ``<`` is converted to ``&lt;``
1414    * ``>`` is converted to ``&gt;``
1415    * ``'`` (single quote) is converted to ``&#39;``
1416    * ``"`` (double quote) is converted to ``&quot;``
1417    * ``&`` is converted to ``&amp;``
1418
1419The escaping is only applied when the string is output, so it does not matter
1420where in a chained sequence of filters you put ``escape``: it will always be
1421applied as though it were the last filter. If you want escaping to be applied
1422immediately, use the ``force_escape`` filter.
1423
1424Applying ``escape`` to a variable that would normally have auto-escaping
1425applied to the result will only result in one round of escaping being done. So
1426it is safe to use this function even in auto-escaping environments. If you want
1427multiple escaping passes to be applied, use the ``force_escape`` filter.
1428
1429.. templatefilter:: escapejs
1430
1431escapejs
1432~~~~~~~~
1433
1434Escapes characters for use in JavaScript strings. This does *not* make the
1435string safe for use in HTML, but does protect you from syntax errors when using
1436templates to generate JavaScript/JSON.
1437
1438For example::
1439
1440    {{ value|escapejs }}
1441
1442If ``value`` is ``"testing\r\njavascript \'string" <b>escaping</b>"``,
1443the output will be ``"testing\\u000D\\u000Ajavascript \\u0027string\\u0022 \\u003Cb\\u003Eescaping\\u003C/b\\u003E"``.
1444
1445.. templatefilter:: filesizeformat
1446
1447filesizeformat
1448~~~~~~~~~~~~~~
1449
1450Format the value like a 'human-readable' file size (i.e. ``'13 KB'``,
1451``'4.1 MB'``, ``'102 bytes'``, etc).
1452
1453For example::
1454
1455    {{ value|filesizeformat }}
1456
1457If ``value`` is 123456789, the output would be ``117.7 MB``.
1458
1459.. templatefilter:: first
1460
1461first
1462~~~~~
1463
1464Returns the first item in a list.
1465
1466For example::
1467
1468    {{ value|first }}
1469
1470If ``value`` is the list ``['a', 'b', 'c']``, the output will be ``'a'``.
1471
1472.. templatefilter:: fix_ampersands
1473
1474fix_ampersands
1475~~~~~~~~~~~~~~
1476
1477.. note::
1478
1479    This is rarely useful as ampersands are automatically escaped. See escape_ for more information.
1480
1481Replaces ampersands with ``&amp;`` entities.
1482
1483For example::
1484
1485    {{ value|fix_ampersands }}
1486
1487If ``value`` is ``Tom & Jerry``, the output will be ``Tom &amp; Jerry``.
1488
1489.. templatefilter:: floatformat
1490
1491floatformat
1492~~~~~~~~~~~
1493
1494When used without an argument, rounds a floating-point number to one decimal
1495place -- but only if there's a decimal part to be displayed. For example:
1496
1497============  ===========================  ========
1498``value``     Template                     Output
1499============  ===========================  ========
1500``34.23234``  ``{{ value|floatformat }}``  ``34.2``
1501``34.00000``  ``{{ value|floatformat }}``  ``34``
1502``34.26000``  ``{{ value|floatformat }}``  ``34.3``
1503============  ===========================  ========
1504
1505If used with a numeric integer argument, ``floatformat`` rounds a number to
1506that many decimal places. For example:
1507
1508============  =============================  ==========
1509``value``     Template                       Output
1510============  =============================  ==========
1511``34.23234``  ``{{ value|floatformat:3 }}``  ``34.232``
1512``34.00000``  ``{{ value|floatformat:3 }}``  ``34.000``
1513``34.26000``  ``{{ value|floatformat:3 }}``  ``34.260``
1514============  =============================  ==========
1515
1516If the argument passed to ``floatformat`` is negative, it will round a number
1517to that many decimal places -- but only if there's a decimal part to be
1518displayed. For example:
1519
1520============  ================================  ==========
1521``value``     Template                          Output
1522============  ================================  ==========
1523``34.23234``  ``{{ value|floatformat:"-3" }}``  ``34.232``
1524``34.00000``  ``{{ value|floatformat:"-3" }}``  ``34``
1525``34.26000``  ``{{ value|floatformat:"-3" }}``  ``34.260``
1526============  ================================  ==========
1527
1528Using ``floatformat`` with no argument is equivalent to using ``floatformat``
1529with an argument of ``-1``.
1530
1531.. templatefilter:: force_escape
1532
1533force_escape
1534~~~~~~~~~~~~
1535
1536Applies HTML escaping to a string (see the ``escape`` filter for details).
1537This filter is applied *immediately* and returns a new, escaped string. This
1538is useful in the rare cases where you need multiple escaping or want to apply
1539other filters to the escaped results. Normally, you want to use the ``escape``
1540filter.
1541
1542.. templatefilter:: get_digit
1543
1544get_digit
1545~~~~~~~~~
1546
1547Given a whole number, returns the requested digit, where 1 is the right-most
1548digit, 2 is the second-right-most digit, etc. Returns the original value for
1549invalid input (if input or argument is not an integer, or if argument is less
1550than 1). Otherwise, output is always an integer.
1551
1552For example::
1553
1554    {{ value|get_digit:"2" }}
1555
1556If ``value`` is ``123456789``, the output will be ``8``.
1557
1558.. templatefilter:: iriencode
1559
1560iriencode
1561~~~~~~~~~
1562
1563Converts an IRI (Internationalized Resource Identifier) to a string that is
1564suitable for including in a URL. This is necessary if you're trying to use
1565strings containing non-ASCII characters in a URL.
1566
1567It's safe to use this filter on a string that has already gone through the
1568``urlencode`` filter.
1569
1570For example::
1571
1572    {{ value|iriencode }}
1573
1574If ``value`` is ``"?test=1&me=2"``, the output will be ``"?test=1&amp;me=2"``.
1575
1576.. templatefilter:: join
1577
1578join
1579~~~~
1580
1581Joins a list with a string, like Python's ``str.join(list)``
1582
1583For example::
1584
1585    {{ value|join:" // " }}
1586
1587If ``value`` is the list ``['a', 'b', 'c']``, the output will be the string
1588``"a // b // c"``.
1589
1590.. templatefilter:: last
1591
1592last
1593~~~~
1594
1595Returns the last item in a list.
1596
1597For example::
1598
1599    {{ value|last }}
1600
1601If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output will be the string
1602``"d"``.
1603
1604.. templatefilter:: length
1605
1606length
1607~~~~~~
1608
1609Returns the length of the value. This works for both strings and lists.
1610
1611For example::
1612
1613    {{ value|length }}
1614
1615If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``4``.
1616
1617.. templatefilter:: length_is
1618
1619length_is
1620~~~~~~~~~
1621
1622Returns ``True`` if the value's length is the argument, or ``False`` otherwise.
1623
1624For example::
1625
1626    {{ value|length_is:"4" }}
1627
1628If ``value`` is ``['a', 'b', 'c', 'd']``, the output will be ``True``.
1629
1630.. templatefilter:: linebreaks
1631
1632linebreaks
1633~~~~~~~~~~
1634
1635Replaces line breaks in plain text with appropriate HTML; a single
1636newline becomes an HTML line break (``<br />``) and a new line
1637followed by a blank line becomes a paragraph break (``</p>``).
1638
1639For example::
1640
1641    {{ value|linebreaks }}
1642
1643If ``value`` is ``Joel\nis a slug``, the output will be ``<p>Joel<br />is a
1644slug</p>``.
1645
1646.. templatefilter:: linebreaksbr
1647
1648linebreaksbr
1649~~~~~~~~~~~~
1650
1651Converts all newlines in a piece of plain text to HTML line breaks
1652(``<br />``).
1653
1654For example::
1655
1656    {{ value|linebreaksbr }}
1657
1658If ``value`` is ``Joel\nis a slug``, the output will be ``Joel<br />is a
1659slug``.
1660
1661.. templatefilter:: linenumbers
1662
1663linenumbers
1664~~~~~~~~~~~
1665
1666Displays text with line numbers.
1667
1668For example::
1669
1670    {{ value|linenumbers }}
1671
1672If ``value`` is::
1673
1674    one
1675    two
1676    three
1677
1678the output will be::
1679
1680    1. one
1681    2. two
1682    3. three
1683
1684.. templatefilter:: ljust
1685
1686ljust
1687~~~~~
1688
1689Left-aligns the value in a field of a given width.
1690
1691**Argument:** field size
1692
1693For example::
1694
1695    "{{ value|ljust:"10" }}"
1696
1697If ``value`` is ``Django``, the output will be ``"Django    "``.
1698
1699.. templatefilter:: lower
1700
1701lower
1702~~~~~
1703
1704Converts a string into all lowercase.
1705
1706For example::
1707
1708    {{ value|lower }}
1709
1710If ``value`` is ``Still MAD At Yoko``, the output will be ``still mad at yoko``.
1711
1712.. templatefilter:: make_list
1713
1714make_list
1715~~~~~~~~~
1716
1717Returns the value turned into a list. For a string, it's a list of characters.
1718For an integer, the argument is cast into an unicode string before creating a
1719list.
1720
1721For example::
1722
1723    {{ value|make_list }}
1724
1725If ``value`` is the string ``"Joel"``, the output would be the list
1726``[u'J', u'o', u'e', u'l']``. If ``value`` is ``123``, the output will be the
1727list ``[u'1', u'2', u'3']``.
1728
1729.. templatefilter:: phone2numeric
1730
1731phone2numeric
1732~~~~~~~~~~~~~
1733
1734Converts a phone number (possibly containing letters) to its numerical
1735equivalent.
1736
1737The input doesn't have to be a valid phone number. This will happily convert
1738any string.
1739
1740For example::
1741
1742    {{ value|phone2numeric }}
1743
1744If ``value`` is ``800-COLLECT``, the output will be ``800-2655328``.
1745
1746.. templatefilter:: pluralize
1747
1748pluralize
1749~~~~~~~~~
1750
1751Returns a plural suffix if the value is not 1. By default, this suffix is ``'s'``.
1752
1753Example::
1754
1755    You have {{ num_messages }} message{{ num_messages|pluralize }}.
1756
1757If ``num_messages`` is ``1``, the output will be ``You have 1 message.``
1758If ``num_messages`` is ``2``  the output will be ``You have 2 messages.``
1759
1760For words that require a suffix other than ``'s'``, you can provide an alternate
1761suffix as a parameter to the filter.
1762
1763Example::
1764
1765    You have {{ num_walruses }} walrus{{ num_walruses|pluralize:"es" }}.
1766
1767For words that don't pluralize by simple suffix, you can specify both a
1768singular and plural suffix, separated by a comma.
1769
1770Example::
1771
1772    You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.
1773
1774.. templatefilter:: pprint
1775
1776pprint
1777~~~~~~
1778
1779A wrapper around `pprint.pprint`__ -- for debugging, really.
1780
1781__ http://docs.python.org/library/pprint.html
1782
1783.. templatefilter:: random
1784
1785random
1786~~~~~~
1787
1788Returns a random item from the given list.
1789
1790For example::
1791
1792    {{ value|random }}
1793
1794If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output could be ``"b"``.
1795
1796.. templatefilter:: removetags
1797
1798removetags
1799~~~~~~~~~~
1800
1801Removes a space-separated list of [X]HTML tags from the output.
1802
1803For example::
1804
1805    {{ value|removetags:"b span"|safe }}
1806
1807If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"`` the
1808output will be ``"Joel <button>is</button> a slug"``.
1809
1810Note that this filter is case-sensitive.
1811
1812If ``value`` is ``"<B>Joel</B> <button>is</button> a <span>slug</span>"`` the
1813output will be ``"<B>Joel</B> <button>is</button> a slug"``.
1814
1815.. templatefilter:: rjust
1816
1817rjust
1818~~~~~
1819
1820Right-aligns the value in a field of a given width.
1821
1822**Argument:** field size
1823
1824For example::
1825
1826    "{{ value|rjust:"10" }}"
1827
1828If ``value`` is ``Django``, the output will be ``"    Django"``.
1829
1830.. templatefilter:: safe
1831
1832safe
1833~~~~
1834
1835Marks a string as not requiring further HTML escaping prior to output. When
1836autoescaping is off, this filter has no effect.
1837
1838.. note::
1839
1840    If you are chaining filters, a filter applied after ``safe`` can
1841    make the contents unsafe again. For example, the following code
1842    prints the variable as is, unescaped:
1843
1844    .. code-block:: html+django
1845
1846        {{ var|safe|escape }}
1847
1848.. templatefilter:: safeseq
1849
1850safeseq
1851~~~~~~~
1852
1853Applies the :tfilter:`safe` filter to each element of a sequence.  Useful in
1854conjunction with other filters that operate on sequences, such as
1855:tfilter:`join`.  For example::
1856
1857    {{ some_list|safeseq|join:", " }}
1858
1859You couldn't use the :tfilter:`safe` filter directly in this case, as it would
1860first convert the variable into a string, rather than working with the
1861individual elements of the sequence.
1862
1863.. templatefilter:: slice
1864
1865slice
1866~~~~~
1867
1868Returns a slice of the list.
1869
1870Uses the same syntax as Python's list slicing. See
1871http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice
1872for an introduction.
1873
1874Example::
1875
1876    {{ some_list|slice:":2" }}
1877
1878If ``some_list`` is ``['a', 'b', 'c']``, the output will be ``['a', 'b']``.
1879
1880.. templatefilter:: slugify
1881
1882slugify
1883~~~~~~~
1884
1885Converts to lowercase, removes non-word characters (alphanumerics and
1886underscores) and converts spaces to hyphens. Also strips leading and trailing
1887whitespace.
1888
1889For example::
1890
1891    {{ value|slugify }}
1892
1893If ``value`` is ``"Joel is a slug"``, the output will be ``"joel-is-a-slug"``.
1894
1895.. templatefilter:: stringformat
1896
1897stringformat
1898~~~~~~~~~~~~
1899
1900Formats the variable according to the argument, a string formatting specifier.
1901This specifier uses Python string formatting syntax, with the exception that
1902the leading "%" is dropped.
1903
1904See http://docs.python.org/library/stdtypes.html#string-formatting-operations
1905for documentation of Python string formatting
1906
1907For example::
1908
1909    {{ value|stringformat:"s" }}
1910
1911If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel is a slug"``.
1912
1913.. templatefilter:: striptags
1914
1915striptags
1916~~~~~~~~~
1917
1918Strips all [X]HTML tags.
1919
1920For example::
1921
1922    {{ value|striptags }}
1923
1924If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"``, the
1925output will be ``"Joel is a slug"``.
1926
1927.. templatefilter:: time
1928
1929time
1930~~~~
1931
1932Formats a time according to the given format.
1933
1934Given format can be the predefined one :setting:`TIME_FORMAT`, or a custom
1935format, same as the :tfilter:`date` filter. Note that the predefined format
1936is locale-dependant.
1937
1938The time filter will only accept parameters in the format string that relate
1939to the time of day, not the date (for obvious reasons). If you need to
1940format a date, use the :tfilter:`date` filter.
1941
1942For example::
1943
1944    {{ value|time:"H:i" }}
1945
1946If ``value`` is equivalent to ``datetime.datetime.now()``, the output will be
1947the string ``"01:23"``.
1948
1949Another example:
1950
1951Assuming that :setting:`USE_L10N` is ``True`` and :setting:`LANGUAGE_CODE` is,
1952for example, ``"de"``, then for::
1953
1954    {{ value|time:"TIME_FORMAT" }}
1955
1956the output will be the string ``"01:23:00"`` (The ``"TIME_FORMAT"`` format
1957specifier for the ``de`` locale as shipped with Django is ``"H:i:s"``).
1958
1959When used without a format string::
1960
1961    {{ value|time }}
1962
1963...the formatting string defined in the :setting:`TIME_FORMAT` setting will be
1964used, without applying any localization.
1965
1966.. versionchanged:: 1.2
1967    Predefined formats can now be influenced by the current locale.
1968
1969.. templatefilter:: timesince
1970
1971timesince
1972~~~~~~~~~
1973
1974Formats a date as the time since that date (e.g., "4 days, 6 hours").
1975
1976Takes an optional argument that is a variable containing the date to use as
1977the comparison point (without the argument, the comparison point is *now*).
1978For example, if ``blog_date`` is a date instance representing midnight on 1
1979June 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006,
1980then ``{{ blog_date|timesince:comment_date }}`` would return "8 hours".
1981
1982Comparing offset-naive and offset-aware datetimes will return an empty string.
1983
1984Minutes is the smallest unit used, and "0 minutes" will be returned for any
1985date that is in the future relative to the comparison point.
1986
1987.. templatefilter:: timeuntil
1988
1989timeuntil
1990~~~~~~~~~
1991
1992Similar to ``timesince``, except that it measures the time from now until the
1993given date or datetime. For example, if today is 1 June 2006 and
1994``conference_date`` is a date instance holding 29 June 2006, then
1995``{{ conference_date|timeuntil }}`` will return "4 weeks".
1996
1997Takes an optional argument that is a variable containing the date to use as
1998the comparison point (instead of *now*). If ``from_date`` contains 22 June
19992006, then ``{{ conference_date|timeuntil:from_date }}`` will return "1 week".
2000
2001Comparing offset-naive and offset-aware datetimes will return an empty string.
2002
2003Minutes is the smallest unit used, and "0 minutes" will be returned for any
2004date that is in the past relative to the comparison point.
2005
2006.. templatefilter:: title
2007
2008title
2009~~~~~
2010
2011Converts a string into titlecase.
2012
2013For example::
2014
2015    {{ value|title }}
2016
2017If ``value`` is ``"my first post"``, the output will be ``"My First Post"``.
2018
2019.. templatefilter:: truncatewords
2020
2021truncatewords
2022~~~~~~~~~~~~~
2023
2024Truncates a string after a certain number of words.
2025
2026**Argument:** Number of words to truncate after
2027
2028For example::
2029
2030    {{ value|truncatewords:2 }}
2031
2032If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel is ..."``.
2033
2034Newlines within the string will be removed.
2035
2036.. templatefilter:: truncatewords_html
2037
2038truncatewords_html
2039~~~~~~~~~~~~~~~~~~
2040
2041Similar to ``truncatewords``, except that it is aware of HTML tags. Any tags
2042that are opened in the string and not closed before the truncation point, are
2043closed immediately after the truncation.
2044
2045This is less efficient than ``truncatewords``, so should only be used when it
2046is being passed HTML text.
2047
2048For example::
2049
2050    {{ value|truncatewords_html:2 }}
2051
2052If ``value`` is ``"<p>Joel is a slug</p>"``, the output will be
2053``"<p>Joel is ...</p>"``.
2054
2055Newlines in the HTML content will be preserved.
2056
2057.. templatefilter:: unordered_list
2058
2059unordered_list
2060~~~~~~~~~~~~~~
2061
2062Recursively takes a self-nested list and returns an HTML unordered list --
2063WITHOUT opening and closing <ul> tags.
2064
2065The list is assumed to be in the proper format. For example, if ``var`` contains
2066``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then
2067``{{ var|unordered_list }}`` would return::
2068
2069    <li>States
2070    <ul>
2071            <li>Kansas
2072            <ul>
2073                    <li>Lawrence</li>
2074                    <li>Topeka</li>
2075            </ul>
2076            </li>
2077            <li>Illinois</li>
2078    </ul>
2079    </li>
2080
2081Note: An older, more restrictive and verbose input format is also supported:
2082``['States', [['Kansas', [['Lawrence', []], ['Topeka', []]]], ['Illinois', []]]]``,
2083
2084.. templatefilter:: upper
2085
2086upper
2087~~~~~
2088
2089Converts a string into all uppercase.
2090
2091For example::
2092
2093    {{ value|upper }}
2094
2095If ``value`` is ``"Joel is a slug"``, the output will be ``"JOEL IS A SLUG"``.
2096
2097.. templatefilter:: urlencode
2098
2099urlencode
2100~~~~~~~~~
2101
2102Escapes a value for use in a URL.
2103
2104For example::
2105
2106    {{ value|urlencode }}
2107
2108If ``value`` is ``"http://www.example.org/foo?a=b&c=d"``, the output will be
2109``"http%3A//www.example.org/foo%3Fa%3Db%26c%3Dd"``.
2110
2111.. versionadded:: 1.3
2112
2113An optional argument containing the characters which should not be escaped can
2114be provided.
2115
2116If not provided, the '/' character is assumed safe. An empty string can be
2117provided when *all* characters should be escaped. For example::
2118
2119    {{ value|urlencode:"" }}
2120
2121If ``value`` is ``"http://www.example.org/"``, the output will be
2122``"http%3A%2F%2Fwww.example.org%2F"``.
2123
2124.. templatefilter:: urlize
2125
2126urlize
2127~~~~~~
2128
2129Converts URLs in text into clickable links.
2130
2131Works on links beginning with ``http://``, ``https://``, or ``www.`` and
2132ending with ``.org``, ``.net`` or ``.com``. Links can have trailing punctuation
2133(periods, commas, close-parens) and leading punctuation (opening parens) and
2134``urlize`` will still do the right thing.
2135
2136Links generated by ``urlize`` have a ``rel="nofollow"`` attribute added
2137to them.
2138
2139For example::
2140
2141    {{ value|urlize }}
2142
2143If ``value`` is ``"Check out www.djangoproject.com"``, the output will be
2144``"Check out <a href="http://www.djangoproject.com"
2145rel="nofollow">www.djangoproject.com</a>"``.
2146
2147The ``urlize`` filter also takes an optional parameter ``autoescape``. If
2148``autoescape`` is ``True``, the link text and URLs will be escaped using
2149Django's built-in :tfilter:`escape` filter. The default value for
2150``autoescape`` is ``True``.
2151
2152.. note::
2153
2154    If ``urlize`` is applied to text that already contains HTML markup,
2155    things won't work as expected. Apply this filter only to plain text.
2156
2157.. templatefilter:: urlizetrunc
2158
2159urlizetrunc
2160~~~~~~~~~~~
2161
2162Converts URLs into clickable links just like urlize_, but truncates URLs
2163longer than the given character limit.
2164
2165**Argument:** Number of characters that link text should be truncated to,
2166including the ellipsis that's added if truncation is necessary.
2167
2168For example::
2169
2170    {{ value|urlizetrunc:15 }}
2171
2172If ``value`` is ``"Check out www.djangoproject.com"``, the output would be
2173``'Check out <a href="http://www.djangoproject.com"
2174rel="nofollow">www.djangopr...</a>'``.
2175
2176As with urlize_, this filter should only be applied to plain text.
2177
2178.. templatefilter:: wordcount
2179
2180wordcount
2181~~~~~~~~~
2182
2183Returns the number of words.
2184
2185For example::
2186
2187    {{ value|wordcount }}
2188
2189If ``value`` is ``"Joel is a slug"``, the output will be ``4``.
2190
2191.. templatefilter:: wordwrap
2192
2193wordwrap
2194~~~~~~~~
2195
2196Wraps words at specified line length.
2197
2198**Argument:** number of characters at which to wrap the text
2199
2200For example::
2201
2202    {{ value|wordwrap:5 }}
2203
2204If ``value`` is ``Joel is a slug``, the output would be::
2205
2206    Joel
2207    is a
2208    slug
2209
2210.. templatefilter:: yesno
2211
2212yesno
2213~~~~~
2214
2215Given a string mapping values for true, false and (optionally) None,
2216returns one of those strings according to the value:
2217
2218For example::
2219
2220    {{ value|yesno:"yeah,no,maybe" }}
2221
2222==========  ======================  ==================================
2223Value       Argument                Outputs
2224==========  ======================  ==================================
2225``True``    ``"yeah,no,maybe"``     ``yeah``
2226``False``   ``"yeah,no,maybe"``     ``no``
2227``None``    ``"yeah,no,maybe"``     ``maybe``
2228``None``    ``"yeah,no"``           ``"no"`` (converts None to False
2229                                    if no mapping for None is given)
2230==========  ======================  ==================================
2231
2232Other tags and filter libraries
2233-------------------------------
2234
2235Django comes with a couple of other template-tag libraries that you have to
2236enable explicitly in your :setting:`INSTALLED_APPS` setting and enable in your
2237template with the ``{% load %}`` tag.
2238
2239django.contrib.humanize
2240~~~~~~~~~~~~~~~~~~~~~~~
2241
2242A set of Django template filters useful for adding a "human touch" to data. See
2243:doc:`/ref/contrib/humanize`.
2244
2245django.contrib.markup
2246~~~~~~~~~~~~~~~~~~~~~
2247
2248A collection of template filters that implement these common markup languages:
2249
2250    * Textile
2251    * Markdown
2252    * reST (reStructuredText)
2253
2254See the :doc:`markup documentation </ref/contrib/markup>`.
2255
2256django.contrib.webdesign
2257~~~~~~~~~~~~~~~~~~~~~~~~
2258
2259A collection of template tags that can be useful while designing a Web site,
2260such as a generator of Lorem Ipsum text. See :doc:`/ref/contrib/webdesign`.
2261
2262i18n
2263~~~~
2264
2265Provides a couple of templatetags that allow specifying translatable text in
2266Django templates. It is slightly different from the libraries described
2267above because you don't need to add any application to the
2268:setting:`INSTALLED_APPS` setting but rather set :setting:`USE_I18N` to True,
2269then loading it with ``{% load i18n %}``.
2270
2271See :ref:`specifying-translation-strings-in-template-code`.
2272
2273l10n
2274~~~~
2275
2276Provides a couple of templatetags that allow control over the localization of
2277values in Django templates. It is slightly different from the libraries described
2278above because you don't need to add any application to the :setting:`INSTALLED_APPS`;
2279you only need to load the library using ``{% load l10n %}``.
2280
2281See :ref:`topic-l10n-templates`.