PageRenderTime 1126ms CodeModel.GetById 143ms app.highlight 161ms RepoModel.GetById 236ms app.codeStats 2ms

/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

Large files files are truncated, but you can click here to view the full 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>`…

Large files files are truncated, but you can click here to view the full file