~ubuntu-branches/ubuntu/saucy/python-django/saucy-updates

« back to all changes in this revision

Viewing changes to docs/ref/templates/builtins.txt

  • Committer: Package Import Robot
  • Author(s): Raphaël Hertzog
  • Date: 2012-03-31 14:48:00 UTC
  • mfrom: (1.2.12)
  • mto: This revision was merged to the branch mainline in revision 38.
  • Revision ID: package-import@ubuntu.com-20120331144800-6a44u7d8z6pd2br4
Tags: upstream-1.4
Import upstream version 1.4

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
.. templatetag:: autoescape
18
18
 
19
19
autoescape
20
 
~~~~~~~~~~
 
20
^^^^^^^^^^
21
21
 
22
 
Control the current auto-escaping behavior. This tag takes either ``on`` or
 
22
Controls the current auto-escaping behavior. This tag takes either ``on`` or
23
23
``off`` as an argument and that determines whether auto-escaping is in effect
24
24
inside the block. The block is closed with an ``endautoescape`` ending tag.
25
25
 
26
26
When auto-escaping is in effect, all variable content has HTML escaping applied
27
27
to it before placing the result into the output (but after any filters have
28
 
been applied). This is equivalent to manually applying the ``escape`` filter
29
 
to each variable.
 
28
been applied). This is equivalent to manually applying the :tfilter:`escape`
 
29
filter to each variable.
30
30
 
31
31
The only exceptions are variables that are already marked as "safe" from
32
32
escaping, either by the code that populated the variable, or because it has had
33
 
the ``safe`` or ``escape`` filters applied.
 
33
the :tfilter:`safe` or :tfilter:`escape` filters applied.
34
34
 
35
35
Sample usage::
36
36
 
41
41
.. templatetag:: block
42
42
 
43
43
block
44
 
~~~~~
 
44
^^^^^
45
45
 
46
 
Define a block that can be overridden by child templates. See
 
46
Defines a block that can be overridden by child templates. See
47
47
:ref:`Template inheritance <template-inheritance>` for more information.
48
48
 
49
49
.. templatetag:: comment
50
50
 
51
51
comment
52
 
~~~~~~~
 
52
^^^^^^^
53
53
 
54
 
Ignore everything between ``{% comment %}`` and ``{% endcomment %}``
 
54
Ignores everything between ``{% comment %}`` and ``{% endcomment %}``.
55
55
 
56
56
.. templatetag:: csrf_token
57
57
 
58
58
csrf_token
59
 
~~~~~~~~~~
 
59
^^^^^^^^^^
60
60
 
61
 
In the Django 1.1.X series, this is a no-op tag that returns an empty string for
62
 
future compatibility purposes.  In Django 1.2 and later, it is used for CSRF
63
 
protection, as described in the documentation for :doc:`Cross Site Request
 
61
In the Django 1.1.X series, this is a no-op tag that returns an empty string
 
62
for future compatibility purposes.  In Django 1.2 and later, it is used for
 
63
CSRF protection, as described in the documentation for :doc:`Cross Site Request
64
64
Forgeries </ref/contrib/csrf>`.
65
65
 
66
66
.. templatetag:: cycle
67
67
 
68
68
cycle
69
 
~~~~~
 
69
^^^^^
70
70
 
71
 
Cycle among the given strings or variables each time this tag is encountered.
 
71
Cycles among the given strings or variables each time this tag is encountered.
72
72
 
73
73
Within a loop, cycles among the given strings each time through the
74
74
loop::
88
88
        </tr>
89
89
    {% endfor %}
90
90
 
91
 
Yes, you can mix variables and strings::
 
91
Note that variable arguments (``rowvalue1`` and ``rowvalue2`` above) are NOT
 
92
auto-escaped! So either make sure that you trust their values, or use explicit
 
93
escaping, like this::
 
94
 
 
95
    {% for o in some_list %}
 
96
        <tr class="{% filter force_escape %}{% cycle rowvalue1 rowvalue2 %}{% endfilter %}">
 
97
            ...
 
98
        </tr>
 
99
    {% endfor %}
 
100
 
 
101
You can mix variables and strings::
92
102
 
93
103
    {% for o in some_list %}
94
104
        <tr class="{% cycle 'row1' rowvalue2 'row3' %}">
137
147
Javascript code contained in the printed variable will be rendered
138
148
as-is, which could potentially lead to security issues.
139
149
 
140
 
If you need to escape the variables in the cycle, you must do so
141
 
explicitly::
142
 
 
143
 
    {% filter force_escape %}
144
 
        {% cycle var1 var2 var3 %}
145
 
    {% endfilter %}
146
 
 
147
150
For backwards compatibility, the ``{% cycle %}`` tag supports the much inferior
148
151
old syntax from previous Django versions. You shouldn't use this in any new
149
152
projects, but for the sake of the people who are still using it, here's what it
187
190
.. templatetag:: debug
188
191
 
189
192
debug
190
 
~~~~~
 
193
^^^^^
191
194
 
192
 
Output a whole load of debugging information, including the current context and
193
 
imported modules.
 
195
Outputs a whole load of debugging information, including the current context
 
196
and imported modules.
194
197
 
195
198
.. templatetag:: extends
196
199
 
197
200
extends
198
 
~~~~~~~
 
201
^^^^^^^
199
202
 
200
 
Signal that this template extends a parent template.
 
203
Signals that this template extends a parent template.
201
204
 
202
205
This tag can be used in two ways:
203
206
 
204
 
   * ``{% extends "base.html" %}`` (with quotes) uses the literal value
205
 
     ``"base.html"`` as the name of the parent template to extend.
 
207
* ``{% extends "base.html" %}`` (with quotes) uses the literal value
 
208
  ``"base.html"`` as the name of the parent template to extend.
206
209
 
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.
 
210
* ``{% extends variable %}`` uses the value of ``variable``. If the variable
 
211
  evaluates to a string, Django will use that string as the name of the
 
212
  parent template. If the variable evaluates to a ``Template`` object,
 
213
  Django will use that object as the parent template.
211
214
 
212
215
See :ref:`template-inheritance` for more information.
213
216
 
214
217
.. templatetag:: filter
215
218
 
216
219
filter
217
 
~~~~~~
 
220
^^^^^^
218
221
 
219
 
Filter the contents of the variable through variable filters.
 
222
Filters the contents of the variable through variable filters.
220
223
 
221
224
Filters can also be piped through each other, and they can have arguments --
222
225
just like in variable syntax.
227
230
        This text will be HTML-escaped, and will appear in all lowercase.
228
231
    {% endfilter %}
229
232
 
 
233
.. note::
 
234
 
 
235
    The :tfilter:`escape` and :tfilter:`safe` filters are not acceptable
 
236
    arguments. Instead, use the :ttag:`autoescape` tag to manage autoescaping
 
237
    for blocks of template code.
 
238
 
230
239
.. templatetag:: firstof
231
240
 
232
241
firstof
233
 
~~~~~~~
 
242
^^^^^^^
234
243
 
235
 
Outputs the first variable passed that is not False, without escaping.
 
244
Outputs the first variable passed that is not False. Does NOT auto-escape
 
245
variable values.
236
246
 
237
247
Outputs nothing if all the passed variables are False.
238
248
 
258
268
Note that the variables included in the firstof tag will not be
259
269
escaped. This is because template tags do not escape their content.
260
270
Any HTML or Javascript code contained in the printed variable will be
261
 
rendered as-is, which could potentially lead to security issues.
262
 
 
263
 
If you need to escape the variables in the firstof tag, you must do so
 
271
rendered as-is, which could potentially lead to security issues. If you
 
272
need to escape the variables in the firstof tag, you must do so
264
273
explicitly::
265
274
 
266
275
    {% filter force_escape %}
270
279
.. templatetag:: for
271
280
 
272
281
for
273
 
~~~
 
282
^^^
274
283
 
275
284
Loop over each item in an array.  For example, to display a list of athletes
276
285
provided in ``athlete_list``::
281
290
    {% endfor %}
282
291
    </ul>
283
292
 
284
 
You can loop over a list in reverse by using ``{% for obj in list reversed %}``.
 
293
You can loop over a list in reverse by using
 
294
``{% for obj in list reversed %}``.
285
295
 
286
296
If you need to loop over a list of lists, you can unpack the values
287
297
in each sub-list into individual variables. For example, if your context
302
312
 
303
313
The for loop sets a number of variables available within the loop:
304
314
 
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
 
    ==========================  ================================================
 
315
==========================  ===============================================
 
316
Variable                    Description
 
317
==========================  ===============================================
 
318
``forloop.counter``         The current iteration of the loop (1-indexed)
 
319
``forloop.counter0``        The current iteration of the loop (0-indexed)
 
320
``forloop.revcounter``      The number of iterations from the end of the
 
321
                            loop (1-indexed)
 
322
``forloop.revcounter0``     The number of iterations from the end of the
 
323
                            loop (0-indexed)
 
324
``forloop.first``           True if this is the first time through the loop
 
325
``forloop.last``            True if this is the last time through the loop
 
326
``forloop.parentloop``      For nested loops, this is the loop "above" the
 
327
                            current one
 
328
==========================  ===============================================
319
329
 
320
330
for ... empty
321
331
^^^^^^^^^^^^^
347
357
.. templatetag:: if
348
358
 
349
359
if
350
 
~~
 
360
^^
351
361
 
352
362
The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e.
353
363
exists, is not empty, and is not a false boolean value) the contents of the
355
365
 
356
366
    {% if athlete_list %}
357
367
        Number of athletes: {{ athlete_list|length }}
 
368
    {% elif athlete_in_locker_room_list %}
 
369
        Athletes should be out of the locker room soon!
358
370
    {% else %}
359
371
        No athletes.
360
372
    {% endif %}
362
374
In the above, if ``athlete_list`` is not empty, the number of athletes will be
363
375
displayed by the ``{{ athlete_list|length }}`` variable.
364
376
 
365
 
As you can see, the ``if`` tag can take an optional ``{% else %}`` clause that
366
 
will be displayed if the test fails.
 
377
As you can see, the ``if`` tag may take one or several `` {% elif %}``
 
378
clauses, as well as an ``{% else %}`` clause that will be displayed if all
 
379
previous conditions fail. These clauses are optional.
 
380
 
 
381
.. versionadded:: 1.4
 
382
 
 
383
The ``if`` tag now supports ``{% elif %}`` clauses.
367
384
 
368
385
Boolean operators
369
386
^^^^^^^^^^^^^^^^^
370
387
 
371
 
``if`` tags may use ``and``, ``or`` or ``not`` to test a number of variables or
372
 
to negate a given variable::
 
388
:ttag:`if` tags may use ``and``, ``or`` or ``not`` to test a number of
 
389
variables or to negate a given variable::
373
390
 
374
391
    {% if athlete_list and coach_list %}
375
392
        Both athletes and coaches are available.
406
423
 
407
424
    if (athlete_list and coach_list) or cheerleader_list
408
425
 
409
 
Use of actual brackets in the ``if`` tag is invalid syntax.  If you need them to
410
 
indicate precedence, you should use nested ``if`` tags.
 
426
Use of actual brackets in the :ttag:`if` tag is invalid syntax.  If you need
 
427
them to indicate precedence, you should use nested :ttag:`if` tags.
411
428
 
412
429
.. versionadded:: 1.2
413
430
 
414
431
 
415
 
``if`` tags may also use the operators ``==``, ``!=``, ``<``, ``>``,
 
432
:ttag:`if` tags may also use the operators ``==``, ``!=``, ``<``, ``>``,
416
433
``<=``, ``>=`` and ``in`` which work as follows:
417
434
 
418
435
 
475
492
^^^^^^^^^^^^^^^
476
493
 
477
494
Contained within. This operator is supported by many Python containers to test
478
 
whether the given value is in the container.  The following are some examples of
479
 
how ``x in y`` will be interpreted::
 
495
whether the given value is in the container.  The following are some examples
 
496
of how ``x in y`` will be interpreted::
480
497
 
481
498
    {% if "bc" in "abcdef" %}
482
499
      This appears since "bc" is a substring of "abcdef"
493
510
    {% endif %}
494
511
 
495
512
``not in`` operator
496
 
~~~~~~~~~~~~~~~~~~~~
 
513
^^^^^^^^^^^^^^^^^^^
497
514
 
498
515
Not contained within.  This is the negation of the ``in`` operator.
499
516
 
511
528
Filters
512
529
^^^^^^^
513
530
 
514
 
You can also use filters in the ``if`` expression. For example::
 
531
You can also use filters in the :ttag:`if` expression. For example::
515
532
 
516
533
    {% if messages|length >= 100 %}
517
534
       You have lots of messages today!
525
542
expression is evaluated - that is, the precedence rules.  The precedence of the
526
543
operators, from lowest to highest, is as follows:
527
544
 
528
 
 * ``or``
529
 
 * ``and``
530
 
 * ``not``
531
 
 * ``in``
532
 
 * ``==``, ``!=``, ``<``, ``>``,``<=``, ``>=``
 
545
* ``or``
 
546
* ``and``
 
547
* ``not``
 
548
* ``in``
 
549
* ``==``, ``!=``, ``<``, ``>``, ``<=``, ``>=``
533
550
 
534
 
(This follows Python exactly). So, for example, the following complex if tag:
 
551
(This follows Python exactly). So, for example, the following complex
 
552
:ttag:`if` tag:
535
553
 
536
554
.. code-block:: django
537
555
 
543
561
 
544
562
    (a == b) or ((c == d) and e)
545
563
 
546
 
If you need different precedence, you will need to use nested if tags. Sometimes
547
 
that is better for clarity anyway, for the sake of those who do not know the
548
 
precedence rules.
 
564
If you need different precedence, you will need to use nested :ttag:`if` tags.
 
565
Sometimes that is better for clarity anyway, for the sake of those who do not
 
566
know the precedence rules.
549
567
 
550
568
 
551
569
.. templatetag:: ifchanged
552
570
 
553
571
ifchanged
554
 
~~~~~~~~~
 
572
^^^^^^^^^
555
573
 
556
574
Check if a value has changed from the last iteration of a loop.
557
575
 
558
 
The 'ifchanged' block tag is used within a loop. It has two possible uses.
 
576
The ``{% ifchanged %}`` block tag is used within a loop. It has two possible
 
577
uses.
559
578
 
560
579
1. Checks its own rendered contents against its previous state and only
561
580
   displays the content if it has changed. For example, this displays a list of
568
587
            <a href="{{ date|date:"M/d"|lower }}/">{{ date|date:"j" }}</a>
569
588
        {% endfor %}
570
589
 
571
 
2. 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::
 
590
2. If given one or more variables, check whether any variable has changed.
 
591
   For example, the following shows the date every time it changes, while
 
592
   showing the hour if either the hour or the date has changed::
574
593
 
575
594
        {% for date in days %}
576
595
            {% ifchanged date.date %} {{ date.date }} {% endifchanged %}
595
614
.. templatetag:: ifequal
596
615
 
597
616
ifequal
598
 
~~~~~~~
 
617
^^^^^^^
599
618
 
600
619
Output the contents of the block if the two arguments equal each other.
601
620
 
605
624
        ...
606
625
    {% endifequal %}
607
626
 
608
 
As in the ``{% if %}`` tag, an ``{% else %}`` clause is optional.
 
627
As in the :ttag:`if` tag, an ``{% else %}`` clause is optional.
609
628
 
610
629
The arguments can be hard-coded strings, so the following is valid::
611
630
 
615
634
 
616
635
It is only possible to compare an argument to template variables or strings.
617
636
You 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``
619
 
tag instead.
 
637
``False``.  If you need to test if something is true or false, use the
 
638
:ttag:`if` tag instead.
620
639
 
621
640
.. versionadded:: 1.2
622
 
   An alternative to the ``ifequal`` tag is to use the :ttag:`if` tag and the ``==`` operator.
 
641
   An alternative to the ``ifequal`` tag is to use the :ttag:`if` tag and the
 
642
   ``==`` operator.
623
643
 
624
644
.. templatetag:: ifnotequal
625
645
 
626
646
ifnotequal
627
 
~~~~~~~~~~
 
647
^^^^^^^^^^
628
648
 
629
 
Just like ``ifequal``, except it tests that the two arguments are not equal.
 
649
Just like :ttag:`ifequal`, except it tests that the two arguments are not
 
650
equal.
630
651
 
631
652
.. versionadded:: 1.2
632
 
   An alternative to the ``ifnotequal`` tag is to use the :ttag:`if` tag and the ``!=`` operator.
 
653
   An alternative to the ``ifnotequal`` tag is to use the :ttag:`if` tag and
 
654
   the ``!=`` operator.
633
655
 
634
656
.. templatetag:: include
635
657
 
636
658
include
637
 
~~~~~~~
 
659
^^^^^^^
638
660
 
639
661
Loads a template and renders it with the current context. This is a way of
640
662
"including" other templates within a template.
654
676
An included template is rendered with the context of the template that's
655
677
including it. This example produces the output ``"Hello, John"``:
656
678
 
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" }}!
 
679
* Context: variable ``person`` is set to ``"john"``.
 
680
* Template::
 
681
 
 
682
    {% include "name_snippet.html" %}
 
683
 
 
684
* The ``name_snippet.html`` template::
 
685
 
 
686
    {{ greeting }}, {{ person|default:"friend" }}!
665
687
 
666
688
.. versionchanged:: 1.3
667
689
   Additional context and exclusive context.
682
704
    This means that there is no shared state between included templates --
683
705
    each include is a completely independent rendering process.
684
706
 
685
 
See also: ``{% ssi %}``.
 
707
See also: :ttag:`{% ssi %}<ssi>`.
686
708
 
687
709
.. templatetag:: load
688
710
 
689
711
load
690
 
~~~~
 
712
^^^^
691
713
 
692
 
Load a custom template tag set.
 
714
Loads a custom template tag set.
693
715
 
694
716
For example, the following template would load all the tags and filters
695
 
registered in ``somelibrary`` and ``otherlibrary``::
 
717
registered in ``somelibrary`` and ``otherlibrary`` located in package
 
718
``package``::
696
719
 
697
 
    {% load somelibrary otherlibrary %}
 
720
    {% load somelibrary package.otherlibrary %}
698
721
 
699
722
.. versionchanged:: 1.3
700
723
 
710
733
.. templatetag:: now
711
734
 
712
735
now
713
 
~~~
 
736
^^^
714
737
 
715
 
Display the current date and/or time, using a format according to the given
 
738
Displays the current date and/or time, using a format according to the given
716
739
string. Such string can contain format specifiers characters as described
717
740
in the :tfilter:`date` filter section.
718
741
 
729
752
 
730
753
This would display as "It is the 4th of September".
731
754
 
 
755
.. versionchanged:: 1.4
 
756
 
 
757
.. note::
 
758
 
 
759
    The format passed can also be one of the predefined ones
 
760
    :setting:`DATE_FORMAT`, :setting:`DATETIME_FORMAT`,
 
761
    :setting:`SHORT_DATE_FORMAT` or :setting:`SHORT_DATETIME_FORMAT`.
 
762
    The predefined formats may vary depending on the current locale and
 
763
    if :ref:`format-localization` is enabled, e.g.::
 
764
 
 
765
        It is {% now "SHORT_DATETIME_FORMAT" %}
 
766
 
732
767
.. templatetag:: regroup
733
768
 
734
769
regroup
735
 
~~~~~~~
 
770
^^^^^^^
736
771
 
737
 
Regroup a list of alike objects by a common attribute.
 
772
Regroups a list of alike objects by a common attribute.
738
773
 
739
774
This complex tag is best illustrated by use of an example: say that ``people``
740
775
is a list of people represented by dictionaries with ``first_name``,
753
788
...and you'd like to display a hierarchical list that is ordered by gender,
754
789
like this:
755
790
 
756
 
    * Male:
757
 
        * George Bush
758
 
        * Bill Clinton
759
 
    * Female:
760
 
        * Margaret Thatcher
761
 
        * Condoleezza Rice
762
 
    * Unknown:
763
 
        * Pat Smith
 
791
* Male:
 
792
 
 
793
  * George Bush
 
794
  * Bill Clinton
 
795
 
 
796
* Female:
 
797
 
 
798
  * Margaret Thatcher
 
799
  * Condoleezza Rice
 
800
 
 
801
* Unknown:
 
802
 
 
803
  * Pat Smith
764
804
 
765
805
You can use the ``{% regroup %}`` tag to group the list of people by gender.
766
806
The following snippet of template code would accomplish this::
787
827
``{% regroup %}`` produces a list (in this case, ``gender_list``) of
788
828
**group objects**. Each group object has two attributes:
789
829
 
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').
 
830
* ``grouper`` -- the item that was grouped by (e.g., the string "Male" or
 
831
  "Female").
 
832
* ``list`` -- a list of all items in this group (e.g., a list of all people
 
833
  with gender='Male').
794
834
 
795
835
Note that ``{% regroup %}`` does not order its input! Our example relies on
796
836
the fact that the ``people`` list was ordered by ``gender`` in the first place.
797
 
If the ``people`` list did *not* order its members by ``gender``, the regrouping
798
 
would naively display more than one group for a single gender. For example,
799
 
say the ``people`` list was set to this (note that the males are not grouped
800
 
together):
 
837
If the ``people`` list did *not* order its members by ``gender``, the
 
838
regrouping would naively display more than one group for a single gender. For
 
839
example, say the ``people`` list was set to this (note that the males are not
 
840
grouped together):
801
841
 
802
842
.. code-block:: python
803
843
 
812
852
With this input for ``people``, the example ``{% regroup %}`` template code
813
853
above would result in the following output:
814
854
 
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
 
855
* Male:
 
856
 
 
857
  * Bill Clinton
 
858
 
 
859
* Unknown:
 
860
 
 
861
  * Pat Smith
 
862
 
 
863
* Female:
 
864
 
 
865
  * Margaret Thatcher
 
866
 
 
867
* Male:
 
868
 
 
869
  * George Bush
 
870
 
 
871
* Female:
 
872
 
 
873
  * Condoleezza Rice
825
874
 
826
875
The easiest solution to this gotcha is to make sure in your view code that the
827
876
data is ordered according to how you want to display it.
828
877
 
829
 
Another solution is to sort the data in the template using the ``dictsort``
830
 
filter, if your data is in a list of dictionaries::
 
878
Another solution is to sort the data in the template using the
 
879
:tfilter:`dictsort` filter, if your data is in a list of dictionaries::
831
880
 
832
881
    {% regroup people|dictsort:"gender" by gender as gender_list %}
833
882
 
843
892
    {% regroup people by gender.description as gender_list %}
844
893
 
845
894
Or, if ``gender`` is a field with ``choices``, it will have a
846
 
:meth:`~django.db.models.Model.get_FOO_display` method available as an
 
895
:meth:`^django.db.models.Model.get_FOO_display` method available as an
847
896
attribute, allowing  you to group on the display string rather than the
848
897
``choices`` key::
849
898
 
855
904
.. templatetag:: spaceless
856
905
 
857
906
spaceless
858
 
~~~~~~~~~
 
907
^^^^^^^^^
859
908
 
860
909
Removes whitespace between HTML tags. This includes tab
861
910
characters and newlines.
884
933
.. templatetag:: ssi
885
934
 
886
935
ssi
887
 
~~~
888
 
 
889
 
Output the contents of a given file into the page.
890
 
 
891
 
Like a simple "include" tag, ``{% ssi %}`` includes the contents of another
892
 
file -- which must be specified using an absolute path -- in the current
893
 
page::
 
936
^^^
 
937
 
 
938
Outputs the contents of a given file into the page.
 
939
 
 
940
Like a simple :ttag:`include` tag, ``{% ssi %}`` includes the contents of
 
941
another file -- which must be specified using an absolute path -- in the
 
942
current page::
894
943
 
895
944
    {% ssi /home/html/ljworld.com/includes/right_generic.html %}
896
945
 
900
949
    {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %}
901
950
 
902
951
Note that if you use ``{% ssi %}``, you'll need to define
903
 
:setting:`ALLOWED_INCLUDE_ROOTS` in your Django settings, as a security measure.
 
952
:setting:`ALLOWED_INCLUDE_ROOTS` in your Django settings, as a security
 
953
measure.
904
954
 
905
 
See also: ``{% include %}``.
 
955
See also: :ttag:`{% include %}<include>`.
906
956
 
907
957
.. admonition:: Forwards compatibility
908
958
 
931
981
.. templatetag:: templatetag
932
982
 
933
983
templatetag
934
 
~~~~~~~~~~~
 
984
^^^^^^^^^^^
935
985
 
936
 
Output one of the syntax characters used to compose template tags.
 
986
Outputs one of the syntax characters used to compose template tags.
937
987
 
938
988
Since the template system has no concept of "escaping", to display one of the
939
989
bits used in template tags, you must use the ``{% templatetag %}`` tag.
940
990
 
941
991
The argument tells which template bit to output:
942
992
 
943
 
    ==================  =======
944
 
    Argument            Outputs
945
 
    ==================  =======
946
 
    ``openblock``       ``{%``
947
 
    ``closeblock``      ``%}``
948
 
    ``openvariable``    ``{{``
949
 
    ``closevariable``   ``}}``
950
 
    ``openbrace``       ``{``
951
 
    ``closebrace``      ``}``
952
 
    ``opencomment``     ``{#``
953
 
    ``closecomment``    ``#}``
954
 
    ==================  =======
 
993
==================  =======
 
994
Argument            Outputs
 
995
==================  =======
 
996
``openblock``       ``{%``
 
997
``closeblock``      ``%}``
 
998
``openvariable``    ``{{``
 
999
``closevariable``   ``}}``
 
1000
``openbrace``       ``{``
 
1001
``closebrace``      ``}``
 
1002
``opencomment``     ``{#``
 
1003
``closecomment``    ``#}``
 
1004
==================  =======
955
1005
 
956
1006
.. templatetag:: url
957
1007
 
958
1008
url
959
 
~~~
 
1009
^^^
960
1010
 
961
1011
Returns an absolute path reference (a URL without the domain name) matching a
962
1012
given view function and optional parameters. This is a way to output links
1002
1052
path to the view.
1003
1053
 
1004
1054
Note that if the URL you're reversing doesn't exist, you'll get an
1005
 
:exc:`~django.core.urlresolvers.NoReverseMatch` exception raised, which will
 
1055
:exc:`^django.core.urlresolvers.NoReverseMatch` exception raised, which will
1006
1056
cause your site to display an error page.
1007
1057
 
1008
1058
If you'd like to retrieve a URL without displaying it, you can use a slightly
1061
1111
    For example::
1062
1112
 
1063
1113
        {% load url from future %}
 
1114
 
 
1115
 
 
1116
        {% url 'app_views.client' %}
 
1117
 
1064
1118
        {% url 'myapp:view-name' %}
1065
1119
 
 
1120
        {% with view_path="app_views.client" %}
 
1121
        {% url view_path client.id %}
 
1122
        {% endwith %}
 
1123
 
 
1124
        {% with url_name="client-detail-view" %}
 
1125
        {% url url_name client.id %}
 
1126
        {% endwith %}
 
1127
 
1066
1128
    The new library also drops support for the comma syntax for
1067
1129
    separating arguments to the :ttag:`url` template tag.
1068
1130
 
1073
1135
.. templatetag:: widthratio
1074
1136
 
1075
1137
widthratio
1076
 
~~~~~~~~~~
 
1138
^^^^^^^^^^
1077
1139
 
1078
 
For creating bar charts and such, this tag calculates the ratio of a given value
1079
 
to a maximum value, and then applies that ratio to a constant.
 
1140
For creating bar charts and such, this tag calculates the ratio of a given
 
1141
value to a maximum value, and then applies that ratio to a constant.
1080
1142
 
1081
1143
For example::
1082
1144
 
1089
1151
.. templatetag:: with
1090
1152
 
1091
1153
with
1092
 
~~~~
 
1154
^^^^
1093
1155
 
1094
1156
.. versionchanged:: 1.3
1095
1157
   New keyword argument format and multiple variable assignments.
1123
1185
.. templatefilter:: add
1124
1186
 
1125
1187
add
1126
 
~~~
 
1188
^^^
1127
1189
 
1128
1190
Adds the argument to the value.
1129
1191
 
1156
1218
.. templatefilter:: addslashes
1157
1219
 
1158
1220
addslashes
1159
 
~~~~~~~~~~
 
1221
^^^^^^^^^^
1160
1222
 
1161
1223
Adds slashes before quotes. Useful for escaping strings in CSV, for example.
1162
1224
 
1164
1226
 
1165
1227
    {{ value|addslashes }}
1166
1228
 
1167
 
If ``value`` is ``"I'm using Django"``, the output will be ``"I\'m using Django"``.
 
1229
If ``value`` is ``"I'm using Django"``, the output will be
 
1230
``"I\'m using Django"``.
1168
1231
 
1169
1232
.. templatefilter:: capfirst
1170
1233
 
1171
1234
capfirst
1172
 
~~~~~~~~
 
1235
^^^^^^^^
1173
1236
 
1174
1237
Capitalizes the first character of the value.
1175
1238
 
1182
1245
.. templatefilter:: center
1183
1246
 
1184
1247
center
1185
 
~~~~~~
 
1248
^^^^^^
1186
1249
 
1187
1250
Centers the value in a field of a given width.
1188
1251
 
1195
1258
.. templatefilter:: cut
1196
1259
 
1197
1260
cut
1198
 
~~~
 
1261
^^^
1199
1262
 
1200
1263
Removes all values of arg from the given string.
1201
1264
 
1203
1266
 
1204
1267
    {{ value|cut:" "}}
1205
1268
 
1206
 
If ``value`` is ``"String with spaces"``, the output will be ``"Stringwithspaces"``.
 
1269
If ``value`` is ``"String with spaces"``, the output will be
 
1270
``"Stringwithspaces"``.
1207
1271
 
1208
1272
.. templatefilter:: date
1209
1273
 
1210
1274
date
1211
 
~~~~
 
1275
^^^^
1212
1276
 
1213
1277
Formats a date according to the given format.
1214
1278
 
1215
 
Uses the same format as PHP's ``date()`` function (http://php.net/date)
1216
 
with some custom extensions.
 
1279
Uses a similar format as PHP's ``date()`` function (http://php.net/date)
 
1280
with some differences.
1217
1281
 
1218
1282
Available format strings:
1219
1283
 
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
 
    ================  ========================================  =====================
 
1284
================  ========================================  =====================
 
1285
Format character  Description                               Example output
 
1286
================  ========================================  =====================
 
1287
a                 ``'a.m.'`` or ``'p.m.'`` (Note that       ``'a.m.'``
 
1288
                  this is slightly different than PHP's
 
1289
                  output, because this includes periods
 
1290
                  to match Associated Press style.)
 
1291
A                 ``'AM'`` or ``'PM'``.                     ``'AM'``
 
1292
b                 Month, textual, 3 letters, lowercase.     ``'jan'``
 
1293
B                 Not implemented.
 
1294
c                 ISO 8601 format. (Note: unlike others     ``2008-01-02T10:30:00.000123+02:00``,
 
1295
                  formatters, such as "Z", "O" or "r",      or ``2008-01-02T10:30:00.000123`` if the datetime is naive
 
1296
                  the "c" formatter will not add timezone
 
1297
                  offset if value is a naive datetime
 
1298
                  (see :class:`datetime.tzinfo`).
 
1299
d                 Day of the month, 2 digits with           ``'01'`` to ``'31'``
 
1300
                  leading zeros.
 
1301
D                 Day of the week, textual, 3 letters.      ``'Fri'``
 
1302
e                 Timezone name. Could be in any format,
 
1303
                  or might return an empty string,          ``''``, ``'GMT'``, ``'-500'``, ``'US/Eastern'``, etc.
 
1304
                  depending on the datetime.
 
1305
E                 Month, locale specific alternative
 
1306
                  representation usually used for long
 
1307
                  date representation.                      ``'listopada'`` (for Polish locale, as opposed to ``'Listopad'``)
 
1308
f                 Time, in 12-hour hours and minutes,       ``'1'``, ``'1:30'``
 
1309
                  with minutes left off if they're zero.
 
1310
                  Proprietary extension.
 
1311
F                 Month, textual, long.                     ``'January'``
 
1312
g                 Hour, 12-hour format without leading      ``'1'`` to ``'12'``
 
1313
                  zeros.
 
1314
G                 Hour, 24-hour format without leading      ``'0'`` to ``'23'``
 
1315
                  zeros.
 
1316
h                 Hour, 12-hour format.                     ``'01'`` to ``'12'``
 
1317
H                 Hour, 24-hour format.                     ``'00'`` to ``'23'``
 
1318
i                 Minutes.                                  ``'00'`` to ``'59'``
 
1319
I                 Not implemented.
 
1320
j                 Day of the month without leading          ``'1'`` to ``'31'``
 
1321
                  zeros.
 
1322
l                 Day of the week, textual, long.           ``'Friday'``
 
1323
L                 Boolean for whether it's a leap year.     ``True`` or ``False``
 
1324
m                 Month, 2 digits with leading zeros.       ``'01'`` to ``'12'``
 
1325
M                 Month, textual, 3 letters.                ``'Jan'``
 
1326
n                 Month without leading zeros.              ``'1'`` to ``'12'``
 
1327
N                 Month abbreviation in Associated Press    ``'Jan.'``, ``'Feb.'``, ``'March'``, ``'May'``
 
1328
                  style. Proprietary extension.
 
1329
o                 ISO-8601 week-numbering year,             ``'1999'``
 
1330
                  corresponding to
 
1331
                  the ISO-8601 week number (W)
 
1332
O                 Difference to Greenwich time in hours.    ``'+0200'``
 
1333
P                 Time, in 12-hour hours, minutes and       ``'1 a.m.'``, ``'1:30 p.m.'``, ``'midnight'``, ``'noon'``, ``'12:30 p.m.'``
 
1334
                  'a.m.'/'p.m.', with minutes left off
 
1335
                  if they're zero and the special-case
 
1336
                  strings 'midnight' and 'noon' if
 
1337
                  appropriate. Proprietary extension.
 
1338
r                 :rfc:`2822` formatted date.               ``'Thu, 21 Dec 2000 16:01:07 +0200'``
 
1339
s                 Seconds, 2 digits with leading zeros.     ``'00'`` to ``'59'``
 
1340
S                 English ordinal suffix for day of the     ``'st'``, ``'nd'``, ``'rd'`` or ``'th'``
 
1341
                  month, 2 characters.
 
1342
t                 Number of days in the given month.        ``28`` to ``31``
 
1343
T                 Time zone of this machine.                ``'EST'``, ``'MDT'``
 
1344
u                 Microseconds.                             ``0`` to ``999999``
 
1345
U                 Seconds since the Unix Epoch
 
1346
                  (January 1 1970 00:00:00 UTC).
 
1347
w                 Day of the week, digits without           ``'0'`` (Sunday) to ``'6'`` (Saturday)
 
1348
                  leading zeros.
 
1349
W                 ISO-8601 week number of year, with        ``1``, ``53``
 
1350
                  weeks starting on Monday.
 
1351
y                 Year, 2 digits.                           ``'99'``
 
1352
Y                 Year, 4 digits.                           ``'1999'``
 
1353
z                 Day of the year.                          ``0`` to ``365``
 
1354
Z                 Time zone offset in seconds. The          ``-43200`` to ``43200``
 
1355
                  offset for timezones west of UTC is
 
1356
                  always negative, and for those east of
 
1357
                  UTC is always positive.
 
1358
================  ========================================  =====================
1285
1359
 
1286
1360
.. versionadded:: 1.2
1287
1361
 
1288
1362
The ``c`` and ``u`` format specification characters were added in Django 1.2.
1289
1363
 
 
1364
.. versionadded:: 1.4
 
1365
 
 
1366
The ``e`` and ``o`` format specification characters were added in Django 1.4.
 
1367
 
1290
1368
For example::
1291
1369
 
1292
1370
    {{ value|date:"D d M Y" }}
1322
1400
.. templatefilter:: default
1323
1401
 
1324
1402
default
1325
 
~~~~~~~
 
1403
^^^^^^^
1326
1404
 
1327
 
If value evaluates to ``False``, use given default. Otherwise, use the value.
 
1405
If value evaluates to ``False``, uses the given default. Otherwise, uses the
 
1406
value.
1328
1407
 
1329
1408
For example::
1330
1409
 
1335
1414
.. templatefilter:: default_if_none
1336
1415
 
1337
1416
default_if_none
1338
 
~~~~~~~~~~~~~~~
 
1417
^^^^^^^^^^^^^^^
1339
1418
 
1340
 
If (and only if) value is ``None``, use given default. Otherwise, use the
 
1419
If (and only if) value is ``None``, uses the given default. Otherwise, uses the
1341
1420
value.
1342
1421
 
1343
1422
Note that if an empty string is given, the default value will *not* be used.
1344
 
Use the ``default`` filter if you want to fallback for empty strings.
 
1423
Use the :tfilter:`default` filter if you want to fallback for empty strings.
1345
1424
 
1346
1425
For example::
1347
1426
 
1352
1431
.. templatefilter:: dictsort
1353
1432
 
1354
1433
dictsort
1355
 
~~~~~~~~
 
1434
^^^^^^^^
1356
1435
 
1357
1436
Takes a list of dictionaries and returns that list sorted by the key given in
1358
1437
the argument.
1384
1463
.. templatefilter:: dictsortreversed
1385
1464
 
1386
1465
dictsortreversed
1387
 
~~~~~~~~~~~~~~~~
 
1466
^^^^^^^^^^^^^^^^
1388
1467
 
1389
1468
Takes a list of dictionaries and returns that list sorted in reverse order by
1390
1469
the key given in the argument. This works exactly the same as the above filter,
1393
1472
.. templatefilter:: divisibleby
1394
1473
 
1395
1474
divisibleby
1396
 
~~~~~~~~~~~
 
1475
^^^^^^^^^^^
1397
1476
 
1398
1477
Returns ``True`` if the value is divisible by the argument.
1399
1478
 
1406
1485
.. templatefilter:: escape
1407
1486
 
1408
1487
escape
1409
 
~~~~~~
 
1488
^^^^^^
1410
1489
 
1411
1490
Escapes a string's HTML. Specifically, it makes these replacements:
1412
1491
 
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;``
 
1492
* ``<`` is converted to ``&lt;``
 
1493
* ``>`` is converted to ``&gt;``
 
1494
* ``'`` (single quote) is converted to ``&#39;``
 
1495
* ``"`` (double quote) is converted to ``&quot;``
 
1496
* ``&`` is converted to ``&amp;``
1418
1497
 
1419
1498
The escaping is only applied when the string is output, so it does not matter
1420
1499
where in a chained sequence of filters you put ``escape``: it will always be
1421
1500
applied as though it were the last filter. If you want escaping to be applied
1422
 
immediately, use the ``force_escape`` filter.
 
1501
immediately, use the :tfilter:`force_escape` filter.
1423
1502
 
1424
1503
Applying ``escape`` to a variable that would normally have auto-escaping
1425
1504
applied to the result will only result in one round of escaping being done. So
1426
1505
it is safe to use this function even in auto-escaping environments. If you want
1427
 
multiple escaping passes to be applied, use the ``force_escape`` filter.
 
1506
multiple escaping passes to be applied, use the :tfilter:`force_escape` filter.
1428
1507
 
1429
1508
.. templatefilter:: escapejs
1430
1509
 
1431
1510
escapejs
1432
 
~~~~~~~~
 
1511
^^^^^^^^
1433
1512
 
1434
1513
Escapes characters for use in JavaScript strings. This does *not* make the
1435
1514
string safe for use in HTML, but does protect you from syntax errors when using
1445
1524
.. templatefilter:: filesizeformat
1446
1525
 
1447
1526
filesizeformat
1448
 
~~~~~~~~~~~~~~
 
1527
^^^^^^^^^^^^^^
1449
1528
 
1450
 
Format the value like a 'human-readable' file size (i.e. ``'13 KB'``,
 
1529
Formats the value like a 'human-readable' file size (i.e. ``'13 KB'``,
1451
1530
``'4.1 MB'``, ``'102 bytes'``, etc).
1452
1531
 
1453
1532
For example::
1459
1538
.. templatefilter:: first
1460
1539
 
1461
1540
first
1462
 
~~~~~
 
1541
^^^^^
1463
1542
 
1464
1543
Returns the first item in a list.
1465
1544
 
1472
1551
.. templatefilter:: fix_ampersands
1473
1552
 
1474
1553
fix_ampersands
1475
 
~~~~~~~~~~~~~~
 
1554
^^^^^^^^^^^^^^
1476
1555
 
1477
1556
.. note::
1478
1557
 
1479
 
    This is rarely useful as ampersands are automatically escaped. See escape_ for more information.
 
1558
    This is rarely useful as ampersands are automatically escaped. See
 
1559
    :tfilter:`escape` for more information.
1480
1560
 
1481
1561
Replaces ampersands with ``&amp;`` entities.
1482
1562
 
1486
1566
 
1487
1567
If ``value`` is ``Tom & Jerry``, the output will be ``Tom &amp; Jerry``.
1488
1568
 
 
1569
However, ampersands used in named entities and numeric character references
 
1570
will not be replaced. For example, if ``value`` is ``Caf&eacute;``, the output
 
1571
will *not* be ``Caf&amp;eacute;`` but remain ``Caf&eacute;``. This means that
 
1572
in some edge cases, such as acronyms followed by semicolons, this filter will
 
1573
not replace ampersands that need replacing. For example, if ``value`` is
 
1574
``Contact the R&D;``, the output will remain unchanged because ``&D;``
 
1575
resembles a named entity.
 
1576
 
1489
1577
.. templatefilter:: floatformat
1490
1578
 
1491
1579
floatformat
1492
 
~~~~~~~~~~~
 
1580
^^^^^^^^^^^
1493
1581
 
1494
1582
When used without an argument, rounds a floating-point number to one decimal
1495
1583
place -- but only if there's a decimal part to be displayed. For example:
1531
1619
.. templatefilter:: force_escape
1532
1620
 
1533
1621
force_escape
1534
 
~~~~~~~~~~~~
 
1622
^^^^^^^^^^^^
1535
1623
 
1536
 
Applies HTML escaping to a string (see the ``escape`` filter for details).
1537
 
This filter is applied *immediately* and returns a new, escaped string. This
1538
 
is useful in the rare cases where you need multiple escaping or want to apply
1539
 
other filters to the escaped results. Normally, you want to use the ``escape``
1540
 
filter.
 
1624
Applies HTML escaping to a string (see the :tfilter:`escape` filter for
 
1625
details). This filter is applied *immediately* and returns a new, escaped
 
1626
string. This is useful in the rare cases where you need multiple escaping or
 
1627
want to apply other filters to the escaped results. Normally, you want to use
 
1628
the :tfilter:`escape` filter.
1541
1629
 
1542
1630
.. templatefilter:: get_digit
1543
1631
 
1544
1632
get_digit
1545
 
~~~~~~~~~
 
1633
^^^^^^^^^
1546
1634
 
1547
1635
Given a whole number, returns the requested digit, where 1 is the right-most
1548
1636
digit, 2 is the second-right-most digit, etc. Returns the original value for
1558
1646
.. templatefilter:: iriencode
1559
1647
 
1560
1648
iriencode
1561
 
~~~~~~~~~
 
1649
^^^^^^^^^
1562
1650
 
1563
1651
Converts an IRI (Internationalized Resource Identifier) to a string that is
1564
1652
suitable for including in a URL. This is necessary if you're trying to use
1565
1653
strings containing non-ASCII characters in a URL.
1566
1654
 
1567
1655
It's safe to use this filter on a string that has already gone through the
1568
 
``urlencode`` filter.
 
1656
:tfilter:`urlencode` filter.
1569
1657
 
1570
1658
For example::
1571
1659
 
1576
1664
.. templatefilter:: join
1577
1665
 
1578
1666
join
1579
 
~~~~
 
1667
^^^^
1580
1668
 
1581
1669
Joins a list with a string, like Python's ``str.join(list)``
1582
1670
 
1590
1678
.. templatefilter:: last
1591
1679
 
1592
1680
last
1593
 
~~~~
 
1681
^^^^
1594
1682
 
1595
1683
Returns the last item in a list.
1596
1684
 
1598
1686
 
1599
1687
    {{ value|last }}
1600
1688
 
1601
 
If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output will be the string
1602
 
``"d"``.
 
1689
If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output will be the
 
1690
string ``"d"``.
1603
1691
 
1604
1692
.. templatefilter:: length
1605
1693
 
1606
1694
length
1607
 
~~~~~~
 
1695
^^^^^^
1608
1696
 
1609
1697
Returns the length of the value. This works for both strings and lists.
1610
1698
 
1617
1705
.. templatefilter:: length_is
1618
1706
 
1619
1707
length_is
1620
 
~~~~~~~~~
 
1708
^^^^^^^^^
1621
1709
 
1622
1710
Returns ``True`` if the value's length is the argument, or ``False`` otherwise.
1623
1711
 
1630
1718
.. templatefilter:: linebreaks
1631
1719
 
1632
1720
linebreaks
1633
 
~~~~~~~~~~
 
1721
^^^^^^^^^^
1634
1722
 
1635
1723
Replaces line breaks in plain text with appropriate HTML; a single
1636
1724
newline becomes an HTML line break (``<br />``) and a new line
1646
1734
.. templatefilter:: linebreaksbr
1647
1735
 
1648
1736
linebreaksbr
1649
 
~~~~~~~~~~~~
 
1737
^^^^^^^^^^^^
1650
1738
 
1651
1739
Converts all newlines in a piece of plain text to HTML line breaks
1652
1740
(``<br />``).
1661
1749
.. templatefilter:: linenumbers
1662
1750
 
1663
1751
linenumbers
1664
 
~~~~~~~~~~~
 
1752
^^^^^^^^^^^
1665
1753
 
1666
1754
Displays text with line numbers.
1667
1755
 
1684
1772
.. templatefilter:: ljust
1685
1773
 
1686
1774
ljust
1687
 
~~~~~
 
1775
^^^^^
1688
1776
 
1689
1777
Left-aligns the value in a field of a given width.
1690
1778
 
1699
1787
.. templatefilter:: lower
1700
1788
 
1701
1789
lower
1702
 
~~~~~
 
1790
^^^^^
1703
1791
 
1704
1792
Converts a string into all lowercase.
1705
1793
 
1707
1795
 
1708
1796
    {{ value|lower }}
1709
1797
 
1710
 
If ``value`` is ``Still MAD At Yoko``, the output will be ``still mad at yoko``.
 
1798
If ``value`` is ``Still MAD At Yoko``, the output will be
 
1799
``still mad at yoko``.
1711
1800
 
1712
1801
.. templatefilter:: make_list
1713
1802
 
1714
1803
make_list
1715
 
~~~~~~~~~
 
1804
^^^^^^^^^
1716
1805
 
1717
1806
Returns the value turned into a list. For a string, it's a list of characters.
1718
1807
For an integer, the argument is cast into an unicode string before creating a
1729
1818
.. templatefilter:: phone2numeric
1730
1819
 
1731
1820
phone2numeric
1732
 
~~~~~~~~~~~~~
 
1821
^^^^^^^^^^^^^
1733
1822
 
1734
1823
Converts a phone number (possibly containing letters) to its numerical
1735
1824
equivalent.
1746
1835
.. templatefilter:: pluralize
1747
1836
 
1748
1837
pluralize
1749
 
~~~~~~~~~
 
1838
^^^^^^^^^
1750
1839
 
1751
 
Returns a plural suffix if the value is not 1. By default, this suffix is ``'s'``.
 
1840
Returns a plural suffix if the value is not 1. By default, this suffix is
 
1841
``'s'``.
1752
1842
 
1753
1843
Example::
1754
1844
 
1771
1861
 
1772
1862
    You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.
1773
1863
 
 
1864
.. note:: Use :ttag:`blocktrans` to pluralize translated strings.
 
1865
 
1774
1866
.. templatefilter:: pprint
1775
1867
 
1776
1868
pprint
1777
 
~~~~~~
1778
 
 
1779
 
A wrapper around `pprint.pprint`__ -- for debugging, really.
1780
 
 
1781
 
__ http://docs.python.org/library/pprint.html
 
1869
^^^^^^
 
1870
 
 
1871
A wrapper around :func:`pprint.pprint` -- for debugging, really.
1782
1872
 
1783
1873
.. templatefilter:: random
1784
1874
 
1785
1875
random
1786
 
~~~~~~
 
1876
^^^^^^
1787
1877
 
1788
1878
Returns a random item from the given list.
1789
1879
 
1796
1886
.. templatefilter:: removetags
1797
1887
 
1798
1888
removetags
1799
 
~~~~~~~~~~
 
1889
^^^^^^^^^^
1800
1890
 
1801
1891
Removes a space-separated list of [X]HTML tags from the output.
1802
1892
 
1815
1905
.. templatefilter:: rjust
1816
1906
 
1817
1907
rjust
1818
 
~~~~~
 
1908
^^^^^
1819
1909
 
1820
1910
Right-aligns the value in a field of a given width.
1821
1911
 
1830
1920
.. templatefilter:: safe
1831
1921
 
1832
1922
safe
1833
 
~~~~
 
1923
^^^^
1834
1924
 
1835
1925
Marks a string as not requiring further HTML escaping prior to output. When
1836
1926
autoescaping is off, this filter has no effect.
1848
1938
.. templatefilter:: safeseq
1849
1939
 
1850
1940
safeseq
1851
 
~~~~~~~
 
1941
^^^^^^^
1852
1942
 
1853
1943
Applies the :tfilter:`safe` filter to each element of a sequence.  Useful in
1854
1944
conjunction with other filters that operate on sequences, such as
1863
1953
.. templatefilter:: slice
1864
1954
 
1865
1955
slice
1866
 
~~~~~
 
1956
^^^^^
1867
1957
 
1868
1958
Returns a slice of the list.
1869
1959
 
1870
1960
Uses the same syntax as Python's list slicing. See
1871
 
http://diveintopython.org/native_data_types/lists.html#odbchelper.list.slice
 
1961
http://diveintopython.net/native_data_types/lists.html#odbchelper.list.slice
1872
1962
for an introduction.
1873
1963
 
1874
1964
Example::
1880
1970
.. templatefilter:: slugify
1881
1971
 
1882
1972
slugify
1883
 
~~~~~~~
 
1973
^^^^^^^
1884
1974
 
1885
1975
Converts to lowercase, removes non-word characters (alphanumerics and
1886
1976
underscores) and converts spaces to hyphens. Also strips leading and trailing
1895
1985
.. templatefilter:: stringformat
1896
1986
 
1897
1987
stringformat
1898
 
~~~~~~~~~~~~
 
1988
^^^^^^^^^^^^
1899
1989
 
1900
1990
Formats the variable according to the argument, a string formatting specifier.
1901
1991
This specifier uses Python string formatting syntax, with the exception that
1913
2003
.. templatefilter:: striptags
1914
2004
 
1915
2005
striptags
1916
 
~~~~~~~~~
 
2006
^^^^^^^^^
1917
2007
 
1918
2008
Strips all [X]HTML tags.
1919
2009
 
1927
2017
.. templatefilter:: time
1928
2018
 
1929
2019
time
1930
 
~~~~
 
2020
^^^^
1931
2021
 
1932
2022
Formats a time according to the given format.
1933
2023
 
1969
2059
.. templatefilter:: timesince
1970
2060
 
1971
2061
timesince
1972
 
~~~~~~~~~
 
2062
^^^^^^^^^
1973
2063
 
1974
2064
Formats a date as the time since that date (e.g., "4 days, 6 hours").
1975
2065
 
1987
2077
.. templatefilter:: timeuntil
1988
2078
 
1989
2079
timeuntil
1990
 
~~~~~~~~~
 
2080
^^^^^^^^^
1991
2081
 
1992
2082
Similar to ``timesince``, except that it measures the time from now until the
1993
2083
given date or datetime. For example, if today is 1 June 2006 and
2006
2096
.. templatefilter:: title
2007
2097
 
2008
2098
title
2009
 
~~~~~
 
2099
^^^^^
2010
2100
 
2011
2101
Converts a string into titlecase.
2012
2102
 
2016
2106
 
2017
2107
If ``value`` is ``"my first post"``, the output will be ``"My First Post"``.
2018
2108
 
 
2109
.. templatefilter:: truncatechars
 
2110
 
 
2111
truncatechars
 
2112
^^^^^^^^^^^^^
 
2113
 
 
2114
.. versionadded:: 1.4
 
2115
 
 
2116
Truncates a string if it is longer than the specified number of characters.
 
2117
Truncated strings will end with a translatable ellipsis sequence ("...").
 
2118
 
 
2119
**Argument:** Number of characters to truncate to
 
2120
 
 
2121
For example::
 
2122
 
 
2123
    {{ value|truncatechars:9 }}
 
2124
 
 
2125
If ``value`` is ``"Joel is a slug"``, the output will be ``"Joel i..."``.
 
2126
 
2019
2127
.. templatefilter:: truncatewords
2020
2128
 
2021
2129
truncatewords
2022
 
~~~~~~~~~~~~~
 
2130
^^^^^^^^^^^^^
2023
2131
 
2024
2132
Truncates a string after a certain number of words.
2025
2133
 
2036
2144
.. templatefilter:: truncatewords_html
2037
2145
 
2038
2146
truncatewords_html
2039
 
~~~~~~~~~~~~~~~~~~
2040
 
 
2041
 
Similar to ``truncatewords``, except that it is aware of HTML tags. Any tags
2042
 
that are opened in the string and not closed before the truncation point, are
2043
 
closed immediately after the truncation.
2044
 
 
2045
 
This is less efficient than ``truncatewords``, so should only be used when it
2046
 
is being passed HTML text.
 
2147
^^^^^^^^^^^^^^^^^^
 
2148
 
 
2149
Similar to :tfilter:`truncatewords`, except that it is aware of HTML tags. Any
 
2150
tags that are opened in the string and not closed before the truncation point,
 
2151
are closed immediately after the truncation.
 
2152
 
 
2153
This is less efficient than :tfilter:`truncatewords`, so should only be used
 
2154
when it is being passed HTML text.
2047
2155
 
2048
2156
For example::
2049
2157
 
2057
2165
.. templatefilter:: unordered_list
2058
2166
 
2059
2167
unordered_list
2060
 
~~~~~~~~~~~~~~
 
2168
^^^^^^^^^^^^^^
2061
2169
 
2062
2170
Recursively takes a self-nested list and returns an HTML unordered list --
2063
2171
WITHOUT opening and closing <ul> tags.
2064
2172
 
2065
 
The list is assumed to be in the proper format. For example, if ``var`` contains
2066
 
``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then
 
2173
The list is assumed to be in the proper format. For example, if ``var``
 
2174
contains ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then
2067
2175
``{{ var|unordered_list }}`` would return::
2068
2176
 
2069
2177
    <li>States
2084
2192
.. templatefilter:: upper
2085
2193
 
2086
2194
upper
2087
 
~~~~~
 
2195
^^^^^
2088
2196
 
2089
2197
Converts a string into all uppercase.
2090
2198
 
2097
2205
.. templatefilter:: urlencode
2098
2206
 
2099
2207
urlencode
2100
 
~~~~~~~~~
 
2208
^^^^^^^^^
2101
2209
 
2102
2210
Escapes a value for use in a URL.
2103
2211
 
2124
2232
.. templatefilter:: urlize
2125
2233
 
2126
2234
urlize
2127
 
~~~~~~
 
2235
^^^^^^
2128
2236
 
2129
2237
Converts URLs in text into clickable links.
2130
2238
 
2131
 
Works on links beginning with ``http://``, ``https://``, or ``www.`` and
2132
 
ending 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.
 
2239
This template tag works on links prefixed with ``http://``, ``https://``, or
 
2240
``www.``. For example, ``http://goo.gl/aia1t`` will get converted but
 
2241
``goo.gl/aia1t`` won't.
 
2242
 
 
2243
It also supports domain-only links ending in one of the original top level
 
2244
domains (``.com``, ``.edu``, ``.gov``, ``.int``, ``.mil``, ``.net``, and
 
2245
``.org``). For example, ``djangoproject.com`` gets converted.
 
2246
 
 
2247
.. versionchanged:: 1.4
 
2248
 
 
2249
Until Django 1.4, only the ``.com``, ``.net`` and ``.org`` suffixes were
 
2250
supported for domain-only links.
 
2251
 
 
2252
Links can have trailing punctuation (periods, commas, close-parens) and leading
 
2253
punctuation (opening parens), and ``urlize`` will still do the right thing.
2135
2254
 
2136
2255
Links generated by ``urlize`` have a ``rel="nofollow"`` attribute added
2137
2256
to them.
2157
2276
.. templatefilter:: urlizetrunc
2158
2277
 
2159
2278
urlizetrunc
2160
 
~~~~~~~~~~~
 
2279
^^^^^^^^^^^
2161
2280
 
2162
2281
Converts URLs into clickable links just like urlize_, but truncates URLs
2163
2282
longer than the given character limit.
2178
2297
.. templatefilter:: wordcount
2179
2298
 
2180
2299
wordcount
2181
 
~~~~~~~~~
 
2300
^^^^^^^^^
2182
2301
 
2183
2302
Returns the number of words.
2184
2303
 
2191
2310
.. templatefilter:: wordwrap
2192
2311
 
2193
2312
wordwrap
2194
 
~~~~~~~~
 
2313
^^^^^^^^
2195
2314
 
2196
2315
Wraps words at specified line length.
2197
2316
 
2210
2329
.. templatefilter:: yesno
2211
2330
 
2212
2331
yesno
2213
 
~~~~~
 
2332
^^^^^
2214
2333
 
2215
 
Given a string mapping values for true, false and (optionally) None,
 
2334
Maps values for true, false and (optionally) None, to the strings "yes", "no",
 
2335
"maybe", or a custom mapping passed as a comma-separated list, and
2216
2336
returns one of those strings according to the value:
2217
2337
 
2218
2338
For example::
2222
2342
==========  ======================  ==================================
2223
2343
Value       Argument                Outputs
2224
2344
==========  ======================  ==================================
 
2345
``True``                            ``yes``
2225
2346
``True``    ``"yeah,no,maybe"``     ``yeah``
2226
2347
``False``   ``"yeah,no,maybe"``     ``no``
2227
2348
``None``    ``"yeah,no,maybe"``     ``maybe``
2229
2350
                                    if no mapping for None is given)
2230
2351
==========  ======================  ==================================
2231
2352
 
2232
 
Other tags and filter libraries
2233
 
-------------------------------
 
2353
Internationalization tags and filters
 
2354
-------------------------------------
 
2355
 
 
2356
Django provides template tags and filters to control each aspect of
 
2357
:doc:`internationalization </topics/i18n/index>` in templates. They allow for
 
2358
granular control of translations, formatting, and time zone conversions.
 
2359
 
 
2360
i18n
 
2361
^^^^
 
2362
 
 
2363
This library allows specifying translatable text in templates.
 
2364
To enable it, set :setting:`USE_I18N` to ``True``, then load it with
 
2365
``{% load i18n %}``.
 
2366
 
 
2367
See :ref:`specifying-translation-strings-in-template-code`.
 
2368
 
 
2369
l10n
 
2370
^^^^
 
2371
 
 
2372
This library provides control over the localization of values in templates.
 
2373
You only need to load the library using ``{% load l10n %}``, but you'll often
 
2374
set :setting:`USE_L10N` to ``True`` so that localization is active by default.
 
2375
 
 
2376
See :ref:`topic-l10n-templates`.
 
2377
 
 
2378
tz
 
2379
^^
 
2380
 
 
2381
.. versionadded:: 1.4
 
2382
 
 
2383
This library provides control over time zone conversions in templates.
 
2384
Like ``l10n``, you only need to load the library using ``{% load tz %}``,
 
2385
but you'll usually also set :setting:`USE_TZ` to ``True`` so that conversion
 
2386
to local time happens by default.
 
2387
 
 
2388
See :ref:`time-zones-in-templates`.
 
2389
 
 
2390
Other tags and filters libraries
 
2391
--------------------------------
2234
2392
 
2235
2393
Django comes with a couple of other template-tag libraries that you have to
2236
2394
enable explicitly in your :setting:`INSTALLED_APPS` setting and enable in your
2237
 
template with the ``{% load %}`` tag.
 
2395
template with the :ttag:`{% load %}<load>` tag.
2238
2396
 
2239
2397
django.contrib.humanize
2240
 
~~~~~~~~~~~~~~~~~~~~~~~
 
2398
^^^^^^^^^^^^^^^^^^^^^^^
2241
2399
 
2242
2400
A set of Django template filters useful for adding a "human touch" to data. See
2243
2401
:doc:`/ref/contrib/humanize`.
2244
2402
 
2245
2403
django.contrib.markup
2246
 
~~~~~~~~~~~~~~~~~~~~~
 
2404
^^^^^^^^^^^^^^^^^^^^^
2247
2405
 
2248
2406
A collection of template filters that implement these common markup languages:
2249
2407
 
2250
 
    * Textile
2251
 
    * Markdown
2252
 
    * reST (reStructuredText)
 
2408
* Textile
 
2409
* Markdown
 
2410
* reST (reStructuredText)
2253
2411
 
2254
2412
See the :doc:`markup documentation </ref/contrib/markup>`.
2255
2413
 
2256
2414
django.contrib.webdesign
2257
 
~~~~~~~~~~~~~~~~~~~~~~~~
 
2415
^^^^^^^^^^^^^^^^^^^^^^^^
2258
2416
 
2259
2417
A collection of template tags that can be useful while designing a Web site,
2260
2418
such as a generator of Lorem Ipsum text. See :doc:`/ref/contrib/webdesign`.
2261
2419
 
2262
 
i18n
2263
 
~~~~
2264
 
 
2265
 
Provides a couple of templatetags that allow specifying translatable text in
2266
 
Django templates. It is slightly different from the libraries described
2267
 
above because you don't need to add any application to the
2268
 
:setting:`INSTALLED_APPS` setting but rather set :setting:`USE_I18N` to True,
2269
 
then loading it with ``{% load i18n %}``.
2270
 
 
2271
 
See :ref:`specifying-translation-strings-in-template-code`.
2272
 
 
2273
 
l10n
2274
 
~~~~
2275
 
 
2276
 
Provides a couple of templatetags that allow control over the localization of
2277
 
values in Django templates. It is slightly different from the libraries described
2278
 
above because you don't need to add any application to the :setting:`INSTALLED_APPS`;
2279
 
you only need to load the library using ``{% load l10n %}``.
2280
 
 
2281
 
See :ref:`topic-l10n-templates`.
 
2420
static
 
2421
^^^^^^
 
2422
 
 
2423
.. templatetag:: static
 
2424
 
 
2425
static
 
2426
""""""
 
2427
 
 
2428
.. highlight:: html+django
 
2429
 
 
2430
To link to static files that are saved in :setting:`STATIC_ROOT` Django ships
 
2431
with a :ttag:`static` template tag. You can use this regardless if you're
 
2432
using :class:`~django.template.RequestContext` or not.
 
2433
 
 
2434
.. code-block:: html+django
 
2435
 
 
2436
    {% load static %}
 
2437
    <img src="{% static "images/hi.jpg" %}" />
 
2438
 
 
2439
It is also able to consume standard context variables, e.g. assuming a
 
2440
``user_stylesheet`` variable is passed to the template:
 
2441
 
 
2442
.. code-block:: html+django
 
2443
 
 
2444
    {% load static %}
 
2445
    <link rel="stylesheet" href="{% static user_stylesheet %}" type="text/css" media="screen" />
 
2446
 
 
2447
.. note::
 
2448
 
 
2449
    The :mod:`staticfiles<django.contrib.staticfiles>` contrib app also ships
 
2450
    with a :ttag:`static template tag<staticfiles-static>` which uses
 
2451
    ``staticfiles'`` :setting:`STATICFILES_STORAGE` to build the URL of the
 
2452
    given path. Use that instead if you have an advanced use case such as
 
2453
    :ref:`using a cloud service to serve static files<staticfiles-from-cdn>`::
 
2454
 
 
2455
        {% load static from staticfiles %}
 
2456
        <img src="{% static "images/hi.jpg" %}" />
 
2457
 
 
2458
.. templatetag:: get_static_prefix
 
2459
 
 
2460
get_static_prefix
 
2461
"""""""""""""""""
 
2462
 
 
2463
.. highlight:: html+django
 
2464
 
 
2465
If you're not using :class:`~django.template.RequestContext`, or if you need
 
2466
more control over exactly where and how :setting:`STATIC_URL` is injected
 
2467
into the template, you can use the :ttag:`get_static_prefix` template tag
 
2468
instead::
 
2469
 
 
2470
    {% load static %}
 
2471
    <img src="{% get_static_prefix %}images/hi.jpg" />
 
2472
 
 
2473
There's also a second form you can use to avoid extra processing if you need
 
2474
the value multiple times::
 
2475
 
 
2476
    {% load static %}
 
2477
    {% get_static_prefix as STATIC_PREFIX %}
 
2478
 
 
2479
    <img src="{{ STATIC_PREFIX }}images/hi.jpg" />
 
2480
    <img src="{{ STATIC_PREFIX }}images/hi2.jpg" />
 
2481
 
 
2482
.. templatetag:: get_media_prefix
 
2483
 
 
2484
get_media_prefix
 
2485
""""""""""""""""
 
2486
 
 
2487
.. highlight:: html+django
 
2488
 
 
2489
Similar to the :ttag:`get_static_prefix`, ``get_media_prefix`` populates a
 
2490
template variable with the media prefix :setting:`MEDIA_URL`, e.g.::
 
2491
 
 
2492
    <script type="text/javascript" charset="utf-8">
 
2493
    var media_path = '{% get_media_prefix %}';
 
2494
    </script>