Added some sphinx cross-reference links to the built-in template tags and filters in multiple areas of the documentation. Also fixed a few minor inconsistencies and did a little PEP8 cleanup while I was at it.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@16922 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Julien Phalip 2011-10-03 08:06:01 +00:00
parent 0d9b6a5bc4
commit c2b9f6496e
11 changed files with 161 additions and 140 deletions

View File

@ -199,7 +199,7 @@ passed around inside the template code:
Internally, these strings are of type ``EscapeString`` or Internally, these strings are of type ``EscapeString`` or
``EscapeUnicode``. Generally you don't have to worry about these; they ``EscapeUnicode``. Generally you don't have to worry about these; they
exist for the implementation of the ``escape`` filter. exist for the implementation of the :tfilter:`escape` filter.
Template filter code falls into one of two situations: Template filter code falls into one of two situations:
@ -501,8 +501,8 @@ safe.
To make sure your template tags are thread safe, you should never store state To make sure your template tags are thread safe, you should never store state
information on the node itself. For example, Django provides a builtin information on the node itself. For example, Django provides a builtin
``cycle`` template tag that cycles among a list of given strings each time it's :ttag:`cycle` template tag that cycles among a list of given strings each time
rendered: it's rendered:
.. code-block:: html+django .. code-block:: html+django

View File

@ -110,7 +110,7 @@ Running a threaded server on a TCP port::
Running a preforked server on a Unix domain socket:: Running a preforked server on a Unix domain socket::
./manage.py runfcgi method=prefork socket=/home/user/mysite.sock pidfile=django.pid ./manage.py runfcgi method=prefork socket=/home/user/mysite.sock pidfile=django.pid
.. admonition:: Socket security .. admonition:: Socket security
Django's default umask requires that the webserver and the Django fastcgi Django's default umask requires that the webserver and the Django fastcgi
@ -223,7 +223,8 @@ This is probably the most common case, if you're using Django's admin site:
.. _mod_rewrite: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html .. _mod_rewrite: http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html
Django will automatically use the pre-rewrite version of the URL when Django will automatically use the pre-rewrite version of the URL when
constructing URLs with the ``{% url %}`` template tag (and similar methods). constructing URLs with the :ttag:`{% url %}<url>` template tag (and similar
methods).
Using mod_fcgid as alternative to mod_fastcgi Using mod_fcgid as alternative to mod_fastcgi
---------------------------------------------- ----------------------------------------------
@ -409,8 +410,8 @@ Because many of these fastcgi-based solutions require rewriting the URL at
some point inside the Web server, the path information that Django sees may not some point inside the Web server, the path information that Django sees may not
resemble the original URL that was passed in. This is a problem if the Django resemble the original URL that was passed in. This is a problem if the Django
application is being served from under a particular prefix and you want your application is being served from under a particular prefix and you want your
URLs from the ``{% url %}`` tag to look like the prefix, rather than the URLs from the :ttag:`{% url %}<url>` tag to look like the prefix, rather than
rewritten version, which might contain, for example, ``mysite.fcgi``. the rewritten version, which might contain, for example, ``mysite.fcgi``.
Django makes a good attempt to work out what the real script name prefix Django makes a good attempt to work out what the real script name prefix
should be. In particular, if the Web server sets the ``SCRIPT_URL`` (specific should be. In particular, if the Web server sets the ``SCRIPT_URL`` (specific

View File

@ -420,9 +420,10 @@ on the object ``poll``. Failing that, it tries an attribute lookup -- which
works, in this case. If attribute lookup had failed, it would've tried a works, in this case. If attribute lookup had failed, it would've tried a
list-index lookup. list-index lookup.
Method-calling happens in the ``{% for %}`` loop: ``poll.choice_set.all`` is Method-calling happens in the :ttag:`{% for %}<for>` loop:
interpreted as the Python code ``poll.choice_set.all()``, which returns an ``poll.choice_set.all`` is interpreted as the Python code
iterable of Choice objects and is suitable for use in the ``{% for %}`` tag. ``poll.choice_set.all()``, which returns an iterable of Choice objects and is
suitable for use in the :ttag:`{% for %}<for>` tag.
See the :doc:`template guide </topics/templates>` for more about templates. See the :doc:`template guide </topics/templates>` for more about templates.

View File

@ -49,13 +49,13 @@ A quick rundown:
data), we need to worry about Cross Site Request Forgeries. data), we need to worry about Cross Site Request Forgeries.
Thankfully, you don't have to worry too hard, because Django comes with Thankfully, you don't have to worry too hard, because Django comes with
a very easy-to-use system for protecting against it. In short, all POST a very easy-to-use system for protecting against it. In short, all POST
forms that are targeted at internal URLs should use the ``{% csrf_token %}`` forms that are targeted at internal URLs should use the
template tag. :ttag:`{% csrf_token %}<csrf_token>` template tag.
The ``{% csrf_token %}`` tag requires information from the request object, which The :ttag:`{% csrf_token %}<csrf_token>` tag requires information from the
is not normally accessible from within the template context. To fix this, a request object, which is not normally accessible from within the template
small adjustment needs to be made to the ``detail`` view, so that it looks like context. To fix this, a small adjustment needs to be made to the ``detail``
the following:: view, so that it looks like the following::
from django.template import RequestContext from django.template import RequestContext
# ... # ...

View File

@ -1962,8 +1962,8 @@ if you specifically wanted the admin view from the admin instance named
For more details, see the documentation on :ref:`reversing namespaced URLs For more details, see the documentation on :ref:`reversing namespaced URLs
<topics-http-reversing-url-namespaces>`. <topics-http-reversing-url-namespaces>`.
To allow easier reversing of the admin urls in templates, Django provides an To allow easier reversing of the admin urls in templates, Django provides an
``admin_url`` filter which takes an action as argument: ``admin_urlname`` filter which takes an action as argument:
.. code-block:: html+django .. code-block:: html+django
@ -1974,5 +1974,5 @@ To allow easier reversing of the admin urls in templates, Django provides an
The action in the examples above match the last part of the URL names for The action in the examples above match the last part of the URL names for
:class:`ModelAdmin` instances described above. The ``opts`` variable can be any :class:`ModelAdmin` instances described above. The ``opts`` variable can be any
object which has an ``app_label`` and ``module_name`` and is usually supplied object which has an ``app_label`` and ``module_name`` and is usually supplied
by the admin views for the current model. by the admin views for the current model.

View File

@ -493,8 +493,9 @@ django.core.context_processors.csrf
.. versionadded:: 1.2 .. versionadded:: 1.2
This processor adds a token that is needed by the ``csrf_token`` template tag This processor adds a token that is needed by the :ttag:`csrf_token` template
for protection against :doc:`Cross Site Request Forgeries </ref/contrib/csrf>`. tag for protection against :doc:`Cross Site Request Forgeries
</ref/contrib/csrf>`.
django.core.context_processors.request django.core.context_processors.request
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

View File

@ -19,18 +19,18 @@ Built-in tag reference
autoescape autoescape
^^^^^^^^^^ ^^^^^^^^^^
Control the current auto-escaping behavior. This tag takes either ``on`` or Controls the current auto-escaping behavior. This tag takes either ``on`` or
``off`` as an argument and that determines whether auto-escaping is in effect ``off`` as an argument and that determines whether auto-escaping is in effect
inside the block. The block is closed with an ``endautoescape`` ending tag. inside the block. The block is closed with an ``endautoescape`` ending tag.
When auto-escaping is in effect, all variable content has HTML escaping applied When auto-escaping is in effect, all variable content has HTML escaping applied
to it before placing the result into the output (but after any filters have to it before placing the result into the output (but after any filters have
been applied). This is equivalent to manually applying the ``escape`` filter been applied). This is equivalent to manually applying the :tfilter:`escape`
to each variable. filter to each variable.
The only exceptions are variables that are already marked as "safe" from The only exceptions are variables that are already marked as "safe" from
escaping, either by the code that populated the variable, or because it has had escaping, either by the code that populated the variable, or because it has had
the ``safe`` or ``escape`` filters applied. the :tfilter:`safe` or :tfilter:`escape` filters applied.
Sample usage:: Sample usage::
@ -43,7 +43,7 @@ Sample usage::
block block
^^^^^ ^^^^^
Define a block that can be overridden by child templates. See Defines a block that can be overridden by child templates. See
:ref:`Template inheritance <template-inheritance>` for more information. :ref:`Template inheritance <template-inheritance>` for more information.
.. templatetag:: comment .. templatetag:: comment
@ -51,16 +51,16 @@ Define a block that can be overridden by child templates. See
comment comment
^^^^^^^ ^^^^^^^
Ignore everything between ``{% comment %}`` and ``{% endcomment %}`` Ignores everything between ``{% comment %}`` and ``{% endcomment %}``
.. templatetag:: csrf_token .. templatetag:: csrf_token
csrf_token csrf_token
^^^^^^^^^^ ^^^^^^^^^^
In the Django 1.1.X series, this is a no-op tag that returns an empty string for In the Django 1.1.X series, this is a no-op tag that returns an empty string
future compatibility purposes. In Django 1.2 and later, it is used for CSRF for future compatibility purposes. In Django 1.2 and later, it is used for
protection, as described in the documentation for :doc:`Cross Site Request CSRF protection, as described in the documentation for :doc:`Cross Site Request
Forgeries </ref/contrib/csrf>`. Forgeries </ref/contrib/csrf>`.
.. templatetag:: cycle .. templatetag:: cycle
@ -68,7 +68,7 @@ Forgeries </ref/contrib/csrf>`.
cycle cycle
^^^^^ ^^^^^
Cycle among the given strings or variables each time this tag is encountered. Cycles among the given strings or variables each time this tag is encountered.
Within a loop, cycles among the given strings each time through the Within a loop, cycles among the given strings each time through the
loop:: loop::
@ -189,15 +189,15 @@ call to ``{% cycle %}`` doesn't specify silent::
debug debug
^^^^^ ^^^^^
Output a whole load of debugging information, including the current context and Outputs a whole load of debugging information, including the current context
imported modules. and imported modules.
.. templatetag:: extends .. templatetag:: extends
extends extends
^^^^^^^ ^^^^^^^
Signal that this template extends a parent template. Signals that this template extends a parent template.
This tag can be used in two ways: This tag can be used in two ways:
@ -216,7 +216,7 @@ See :ref:`template-inheritance` for more information.
filter filter
^^^^^^ ^^^^^^
Filter the contents of the variable through variable filters. Filters the contents of the variable through variable filters.
Filters can also be piped through each other, and they can have arguments -- Filters can also be piped through each other, and they can have arguments --
just like in variable syntax. just like in variable syntax.
@ -281,7 +281,8 @@ provided in ``athlete_list``::
{% endfor %} {% endfor %}
</ul> </ul>
You can loop over a list in reverse by using ``{% for obj in list reversed %}``. You can loop over a list in reverse by using
``{% for obj in list reversed %}``.
If you need to loop over a list of lists, you can unpack the values If you need to loop over a list of lists, you can unpack the values
in each sub-list into individual variables. For example, if your context in each sub-list into individual variables. For example, if your context
@ -302,9 +303,9 @@ would display the keys and values of the dictionary::
The for loop sets a number of variables available within the loop: The for loop sets a number of variables available within the loop:
========================== ================================================ ========================== ===============================================
Variable Description Variable Description
========================== ================================================ ========================== ===============================================
``forloop.counter`` The current iteration of the loop (1-indexed) ``forloop.counter`` The current iteration of the loop (1-indexed)
``forloop.counter0`` The current iteration of the loop (0-indexed) ``forloop.counter0`` The current iteration of the loop (0-indexed)
``forloop.revcounter`` The number of iterations from the end of the ``forloop.revcounter`` The number of iterations from the end of the
@ -315,7 +316,7 @@ The for loop sets a number of variables available within the loop:
``forloop.last`` True if this is the last time through the loop ``forloop.last`` True if this is the last time through the loop
``forloop.parentloop`` For nested loops, this is the loop "above" the ``forloop.parentloop`` For nested loops, this is the loop "above" the
current one current one
========================== ================================================ ========================== ===============================================
for ... empty for ... empty
^^^^^^^^^^^^^ ^^^^^^^^^^^^^
@ -368,8 +369,8 @@ will be displayed if the test fails.
Boolean operators Boolean operators
^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^
``if`` tags may use ``and``, ``or`` or ``not`` to test a number of variables or :ttag:`if` tags may use ``and``, ``or`` or ``not`` to test a number of
to negate a given variable:: variables or to negate a given variable::
{% if athlete_list and coach_list %} {% if athlete_list and coach_list %}
Both athletes and coaches are available. Both athletes and coaches are available.
@ -406,13 +407,13 @@ will be interpreted like:
if (athlete_list and coach_list) or cheerleader_list if (athlete_list and coach_list) or cheerleader_list
Use of actual brackets in the ``if`` tag is invalid syntax. If you need them to Use of actual brackets in the :ttag:`if` tag is invalid syntax. If you need
indicate precedence, you should use nested ``if`` tags. them to indicate precedence, you should use nested :ttag:`if` tags.
.. versionadded:: 1.2 .. versionadded:: 1.2
``if`` tags may also use the operators ``==``, ``!=``, ``<``, ``>``, :ttag:`if` tags may also use the operators ``==``, ``!=``, ``<``, ``>``,
``<=``, ``>=`` and ``in`` which work as follows: ``<=``, ``>=`` and ``in`` which work as follows:
@ -475,8 +476,8 @@ Greater than or equal to. Example::
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
Contained within. This operator is supported by many Python containers to test Contained within. This operator is supported by many Python containers to test
whether the given value is in the container. The following are some examples of whether the given value is in the container. The following are some examples
how ``x in y`` will be interpreted:: of how ``x in y`` will be interpreted::
{% if "bc" in "abcdef" %} {% if "bc" in "abcdef" %}
This appears since "bc" is a substring of "abcdef" This appears since "bc" is a substring of "abcdef"
@ -511,7 +512,7 @@ you should use::
Filters Filters
^^^^^^^ ^^^^^^^
You can also use filters in the ``if`` expression. For example:: You can also use filters in the :ttag:`if` expression. For example::
{% if messages|length >= 100 %} {% if messages|length >= 100 %}
You have lots of messages today! You have lots of messages today!
@ -531,7 +532,8 @@ operators, from lowest to highest, is as follows:
* ``in`` * ``in``
* ``==``, ``!=``, ``<``, ``>``, ``<=``, ``>=`` * ``==``, ``!=``, ``<``, ``>``, ``<=``, ``>=``
(This follows Python exactly). So, for example, the following complex if tag: (This follows Python exactly). So, for example, the following complex
:ttag:`if` tag:
.. code-block:: django .. code-block:: django
@ -543,9 +545,9 @@ operators, from lowest to highest, is as follows:
(a == b) or ((c == d) and e) (a == b) or ((c == d) and e)
If you need different precedence, you will need to use nested if tags. Sometimes If you need different precedence, you will need to use nested :ttag:`if` tags.
that is better for clarity anyway, for the sake of those who do not know the Sometimes that is better for clarity anyway, for the sake of those who do not
precedence rules. know the precedence rules.
.. templatetag:: ifchanged .. templatetag:: ifchanged
@ -606,7 +608,7 @@ Example::
... ...
{% endifequal %} {% endifequal %}
As in the ``{% if %}`` tag, an ``{% else %}`` clause is optional. As in the :ttag:`if` tag, an ``{% else %}`` clause is optional.
The arguments can be hard-coded strings, so the following is valid:: The arguments can be hard-coded strings, so the following is valid::
@ -616,21 +618,24 @@ The arguments can be hard-coded strings, so the following is valid::
It is only possible to compare an argument to template variables or strings. It is only possible to compare an argument to template variables or strings.
You cannot check for equality with Python objects such as ``True`` or You cannot check for equality with Python objects such as ``True`` or
``False``. If you need to test if something is true or false, use the ``if`` ``False``. If you need to test if something is true or false, use the
tag instead. :ttag:`if` tag instead.
.. versionadded:: 1.2 .. versionadded:: 1.2
An alternative to the ``ifequal`` tag is to use the :ttag:`if` tag and the ``==`` operator. An alternative to the ``ifequal`` tag is to use the :ttag:`if` tag and the
``==`` operator.
.. templatetag:: ifnotequal .. templatetag:: ifnotequal
ifnotequal ifnotequal
^^^^^^^^^^ ^^^^^^^^^^
Just like ``ifequal``, except it tests that the two arguments are not equal. Just like :ttag:`ifequal`, except it tests that the two arguments are not
equal.
.. versionadded:: 1.2 .. versionadded:: 1.2
An alternative to the ``ifnotequal`` tag is to use the :ttag:`if` tag and the ``!=`` operator. An alternative to the ``ifnotequal`` tag is to use the :ttag:`if` tag and
the ``!=`` operator.
.. templatetag:: include .. templatetag:: include
@ -683,14 +688,14 @@ no variables at all), use the ``only`` option::
This means that there is no shared state between included templates -- This means that there is no shared state between included templates --
each include is a completely independent rendering process. each include is a completely independent rendering process.
See also: ``{% ssi %}``. See also: :ttag:`{% ssi %}<ssi>`.
.. templatetag:: load .. templatetag:: load
load load
^^^^ ^^^^
Load a custom template tag set. Loads a custom template tag set.
For example, the following template would load all the tags and filters For example, the following template would load all the tags and filters
registered in ``somelibrary`` and ``otherlibrary``:: registered in ``somelibrary`` and ``otherlibrary``::
@ -713,7 +718,7 @@ more information.
now now
^^^ ^^^
Display the current date and/or time, using a format according to the given Displays the current date and/or time, using a format according to the given
string. Such string can contain format specifiers characters as described string. Such string can contain format specifiers characters as described
in the :tfilter:`date` filter section. in the :tfilter:`date` filter section.
@ -747,7 +752,7 @@ This would display as "It is the 4th of September".
regroup regroup
^^^^^^^ ^^^^^^^
Regroup a list of alike objects by a common attribute. Regroups a list of alike objects by a common attribute.
This complex tag is best illustrated by use of an example: say that ``people`` This complex tag is best illustrated by use of an example: say that ``people``
is a list of people represented by dictionaries with ``first_name``, is a list of people represented by dictionaries with ``first_name``,
@ -807,10 +812,10 @@ attribute and calling the result ``gender_list``.
Note that ``{% regroup %}`` does not order its input! Our example relies on Note that ``{% regroup %}`` does not order its input! Our example relies on
the fact that the ``people`` list was ordered by ``gender`` in the first place. the fact that the ``people`` list was ordered by ``gender`` in the first place.
If the ``people`` list did *not* order its members by ``gender``, the regrouping If the ``people`` list did *not* order its members by ``gender``, the
would naively display more than one group for a single gender. For example, regrouping would naively display more than one group for a single gender. For
say the ``people`` list was set to this (note that the males are not grouped example, say the ``people`` list was set to this (note that the males are not
together): grouped together):
.. code-block:: python .. code-block:: python
@ -839,8 +844,8 @@ above would result in the following output:
The easiest solution to this gotcha is to make sure in your view code that the The easiest solution to this gotcha is to make sure in your view code that the
data is ordered according to how you want to display it. data is ordered according to how you want to display it.
Another solution is to sort the data in the template using the ``dictsort`` Another solution is to sort the data in the template using the
filter, if your data is in a list of dictionaries:: :tfilter:`dictsort` filter, if your data is in a list of dictionaries::
{% regroup people|dictsort:"gender" by gender as gender_list %} {% regroup people|dictsort:"gender" by gender as gender_list %}
@ -899,11 +904,11 @@ this example, the space around ``Hello`` won't be stripped::
ssi ssi
^^^ ^^^
Output the contents of a given file into the page. Outputs the contents of a given file into the page.
Like a simple "include" tag, ``{% ssi %}`` includes the contents of another Like a simple :ttag:`include` tag, ``{% ssi %}`` includes the contents of
file -- which must be specified using an absolute path -- in the current another file -- which must be specified using an absolute path -- in the
page:: current page::
{% ssi /home/html/ljworld.com/includes/right_generic.html %} {% ssi /home/html/ljworld.com/includes/right_generic.html %}
@ -913,9 +918,10 @@ file are evaluated as template code, within the current context::
{% ssi /home/html/ljworld.com/includes/right_generic.html parsed %} {% ssi /home/html/ljworld.com/includes/right_generic.html parsed %}
Note that if you use ``{% ssi %}``, you'll need to define Note that if you use ``{% ssi %}``, you'll need to define
:setting:`ALLOWED_INCLUDE_ROOTS` in your Django settings, as a security measure. :setting:`ALLOWED_INCLUDE_ROOTS` in your Django settings, as a security
measure.
See also: ``{% include %}``. See also: :ttag:`{% include %}<include>`.
.. admonition:: Forwards compatibility .. admonition:: Forwards compatibility
@ -946,7 +952,7 @@ See also: ``{% include %}``.
templatetag templatetag
^^^^^^^^^^^ ^^^^^^^^^^^
Output one of the syntax characters used to compose template tags. Outputs one of the syntax characters used to compose template tags.
Since the template system has no concept of "escaping", to display one of the Since the template system has no concept of "escaping", to display one of the
bits used in template tags, you must use the ``{% templatetag %}`` tag. bits used in template tags, you must use the ``{% templatetag %}`` tag.
@ -1100,8 +1106,8 @@ projects?
widthratio widthratio
^^^^^^^^^^ ^^^^^^^^^^
For creating bar charts and such, this tag calculates the ratio of a given value For creating bar charts and such, this tag calculates the ratio of a given
to a maximum value, and then applies that ratio to a constant. value to a maximum value, and then applies that ratio to a constant.
For example:: For example::
@ -1189,7 +1195,8 @@ For example::
{{ value|addslashes }} {{ value|addslashes }}
If ``value`` is ``"I'm using Django"``, the output will be ``"I\'m using Django"``. If ``value`` is ``"I'm using Django"``, the output will be
``"I\'m using Django"``.
.. templatefilter:: capfirst .. templatefilter:: capfirst
@ -1228,7 +1235,8 @@ For example::
{{ value|cut:" "}} {{ value|cut:" "}}
If ``value`` is ``"String with spaces"``, the output will be ``"Stringwithspaces"``. If ``value`` is ``"String with spaces"``, the output will be
``"Stringwithspaces"``.
.. templatefilter:: date .. templatefilter:: date
@ -1353,7 +1361,8 @@ used, without applying any localization.
default default
^^^^^^^ ^^^^^^^
If value evaluates to ``False``, use given default. Otherwise, use the value. If value evaluates to ``False``, uses the given default. Otherwise, uses the
value.
For example:: For example::
@ -1366,11 +1375,11 @@ If ``value`` is ``""`` (the empty string), the output will be ``nothing``.
default_if_none default_if_none
^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^
If (and only if) value is ``None``, use given default. Otherwise, use the If (and only if) value is ``None``, uses the given default. Otherwise, uses the
value. value.
Note that if an empty string is given, the default value will *not* be used. Note that if an empty string is given, the default value will *not* be used.
Use the ``default`` filter if you want to fallback for empty strings. Use the :tfilter:`default` filter if you want to fallback for empty strings.
For example:: For example::
@ -1448,12 +1457,12 @@ Escapes a string's HTML. Specifically, it makes these replacements:
The escaping is only applied when the string is output, so it does not matter The escaping is only applied when the string is output, so it does not matter
where in a chained sequence of filters you put ``escape``: it will always be where in a chained sequence of filters you put ``escape``: it will always be
applied as though it were the last filter. If you want escaping to be applied applied as though it were the last filter. If you want escaping to be applied
immediately, use the ``force_escape`` filter. immediately, use the :tfilter:`force_escape` filter.
Applying ``escape`` to a variable that would normally have auto-escaping Applying ``escape`` to a variable that would normally have auto-escaping
applied to the result will only result in one round of escaping being done. So applied to the result will only result in one round of escaping being done. So
it is safe to use this function even in auto-escaping environments. If you want it is safe to use this function even in auto-escaping environments. If you want
multiple escaping passes to be applied, use the ``force_escape`` filter. multiple escaping passes to be applied, use the :tfilter:`force_escape` filter.
.. templatefilter:: escapejs .. templatefilter:: escapejs
@ -1476,7 +1485,7 @@ the output will be ``"testing\\u000D\\u000Ajavascript \\u0027string\\u0022 \\u00
filesizeformat filesizeformat
^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^
Format the value like a 'human-readable' file size (i.e. ``'13 KB'``, Formats the value like a 'human-readable' file size (i.e. ``'13 KB'``,
``'4.1 MB'``, ``'102 bytes'``, etc). ``'4.1 MB'``, ``'102 bytes'``, etc).
For example:: For example::
@ -1505,7 +1514,8 @@ fix_ampersands
.. note:: .. note::
This is rarely useful as ampersands are automatically escaped. See escape_ for more information. This is rarely useful as ampersands are automatically escaped. See
:tfilter:`escape` for more information.
Replaces ampersands with ``&amp;`` entities. Replaces ampersands with ``&amp;`` entities.
@ -1570,11 +1580,11 @@ with an argument of ``-1``.
force_escape force_escape
^^^^^^^^^^^^ ^^^^^^^^^^^^
Applies HTML escaping to a string (see the ``escape`` filter for details). Applies HTML escaping to a string (see the :tfilter:`escape` filter for
This filter is applied *immediately* and returns a new, escaped string. This details). This filter is applied *immediately* and returns a new, escaped
is useful in the rare cases where you need multiple escaping or want to apply string. This is useful in the rare cases where you need multiple escaping or
other filters to the escaped results. Normally, you want to use the ``escape`` want to apply other filters to the escaped results. Normally, you want to use
filter. the :tfilter:`escape` filter.
.. templatefilter:: get_digit .. templatefilter:: get_digit
@ -1602,7 +1612,7 @@ suitable for including in a URL. This is necessary if you're trying to use
strings containing non-ASCII characters in a URL. strings containing non-ASCII characters in a URL.
It's safe to use this filter on a string that has already gone through the It's safe to use this filter on a string that has already gone through the
``urlencode`` filter. :tfilter:`urlencode` filter.
For example:: For example::
@ -1635,8 +1645,8 @@ For example::
{{ value|last }} {{ value|last }}
If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output will be the string If ``value`` is the list ``['a', 'b', 'c', 'd']``, the output will be the
``"d"``. string ``"d"``.
.. templatefilter:: length .. templatefilter:: length
@ -1744,7 +1754,8 @@ For example::
{{ value|lower }} {{ value|lower }}
If ``value`` is ``Still MAD At Yoko``, the output will be ``still mad at yoko``. If ``value`` is ``Still MAD At Yoko``, the output will be
``still mad at yoko``.
.. templatefilter:: make_list .. templatefilter:: make_list
@ -1785,7 +1796,8 @@ If ``value`` is ``800-COLLECT``, the output will be ``800-2655328``.
pluralize pluralize
^^^^^^^^^ ^^^^^^^^^
Returns a plural suffix if the value is not 1. By default, this suffix is ``'s'``. Returns a plural suffix if the value is not 1. By default, this suffix is
``'s'``.
Example:: Example::
@ -2093,12 +2105,12 @@ Newlines within the string will be removed.
truncatewords_html truncatewords_html
^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^
Similar to ``truncatewords``, except that it is aware of HTML tags. Any tags Similar to :tfilter:`truncatewords`, except that it is aware of HTML tags. Any
that are opened in the string and not closed before the truncation point, are tags that are opened in the string and not closed before the truncation point,
closed immediately after the truncation. are closed immediately after the truncation.
This is less efficient than ``truncatewords``, so should only be used when it This is less efficient than :tfilter:`truncatewords`, so should only be used
is being passed HTML text. when it is being passed HTML text.
For example:: For example::
@ -2117,8 +2129,8 @@ unordered_list
Recursively takes a self-nested list and returns an HTML unordered list -- Recursively takes a self-nested list and returns an HTML unordered list --
WITHOUT opening and closing <ul> tags. WITHOUT opening and closing <ul> tags.
The list is assumed to be in the proper format. For example, if ``var`` contains The list is assumed to be in the proper format. For example, if ``var``
``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then contains ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then
``{{ var|unordered_list }}`` would return:: ``{{ var|unordered_list }}`` would return::
<li>States <li>States
@ -2295,7 +2307,7 @@ Other tags and filter libraries
Django comes with a couple of other template-tag libraries that you have to Django comes with a couple of other template-tag libraries that you have to
enable explicitly in your :setting:`INSTALLED_APPS` setting and enable in your enable explicitly in your :setting:`INSTALLED_APPS` setting and enable in your
template with the ``{% load %}`` tag. template with the :ttag:`{% load %}<load>` tag.
django.contrib.humanize django.contrib.humanize
^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^
@ -2335,9 +2347,10 @@ l10n
^^^^ ^^^^
Provides a couple of templatetags that allow control over the localization of Provides a couple of templatetags that allow control over the localization of
values in Django templates. It is slightly different from the libraries described values in Django templates. It is slightly different from the libraries
above because you don't need to add any application to the :setting:`INSTALLED_APPS`; described above because you don't need to add any application to the
you only need to load the library using ``{% load l10n %}``. :setting:`INSTALLED_APPS`; you only need to load the library using
``{% load l10n %}``.
See :ref:`topic-l10n-templates`. See :ref:`topic-l10n-templates`.

View File

@ -587,6 +587,8 @@ Here's the same thing, with ``my_view`` wrapped in ``cache_page``::
(r'^foo/(\d{1,2})/$', cache_page(60 * 15)(my_view)), (r'^foo/(\d{1,2})/$', cache_page(60 * 15)(my_view)),
) )
.. templatetag:: cache
Template fragment caching Template fragment caching
========================= =========================

View File

@ -225,8 +225,8 @@ It is optimal because:
1. Since QuerySets are lazy, this does no database queries if 'display_inbox' 1. Since QuerySets are lazy, this does no database queries if 'display_inbox'
is False. is False.
#. Use of ``with`` means that we store ``user.emails.all`` in a variable for #. Use of :ttag:`with` means that we store ``user.emails.all`` in a variable
later use, allowing its cache to be re-used. for later use, allowing its cache to be re-used.
#. The line ``{% if emails %}`` causes ``QuerySet.__nonzero__()`` to be called, #. The line ``{% if emails %}`` causes ``QuerySet.__nonzero__()`` to be called,
which causes the ``user.emails.all()`` query to be run on the database, and which causes the ``user.emails.all()`` query to be run on the database, and
@ -236,10 +236,10 @@ It is optimal because:
#. The use of ``{{ emails|length }}`` calls ``QuerySet.__len__()``, filling #. The use of ``{{ emails|length }}`` calls ``QuerySet.__len__()``, filling
out the rest of the cache without doing another query. out the rest of the cache without doing another query.
#. The ``for`` loop iterates over the already filled cache. #. The :ttag:`for` loop iterates over the already filled cache.
In total, this code does either one or zero database queries. The only In total, this code does either one or zero database queries. The only
deliberate optimization performed is the use of the ``with`` tag. Using deliberate optimization performed is the use of the :ttag:`with` tag. Using
``QuerySet.exists()`` or ``QuerySet.count()`` at any point would cause ``QuerySet.exists()`` or ``QuerySet.count()`` at any point would cause
additional queries. additional queries.

View File

@ -425,6 +425,8 @@ Translations in :doc:`Django templates </topics/templates>` uses two template
tags and a slightly different syntax than in Python code. To give your template tags and a slightly different syntax than in Python code. To give your template
access to these tags, put ``{% load i18n %}`` toward the top of your template. access to these tags, put ``{% load i18n %}`` toward the top of your template.
.. templatetag:: trans
``trans`` template tag ``trans`` template tag
---------------------- ----------------------
@ -485,7 +487,7 @@ or should be used as arguments for other template tags or filters::
.. versionchanged:: 1.3 .. versionchanged:: 1.3
New keyword argument format. New keyword argument format.
Contrarily to the ``trans`` tag, the ``blocktrans`` tag allows you to mark Contrarily to the :ttag:`trans` tag, the ``blocktrans`` tag allows you to mark
complex sentences consisting of literals and variable content for translation complex sentences consisting of literals and variable content for translation
by making use of placeholders:: by making use of placeholders::

View File

@ -110,8 +110,8 @@ Filters
You can modify variables for display by using **filters**. You can modify variables for display by using **filters**.
Filters look like this: ``{{ name|lower }}``. This displays the value of the Filters look like this: ``{{ name|lower }}``. This displays the value of the
``{{ name }}`` variable after being filtered through the ``lower`` filter, ``{{ name }}`` variable after being filtered through the :tfilter:`lower`
which converts text to lowercase. Use a pipe (``|``) to apply a filter. filter, which converts text to lowercase. Use a pipe (``|``) to apply a filter.
Filters can be "chained." The output of one filter is applied to the next. Filters can be "chained." The output of one filter is applied to the next.
``{{ text|escape|linebreaks }}`` is a common idiom for escaping text contents, ``{{ text|escape|linebreaks }}`` is a common idiom for escaping text contents,
@ -121,13 +121,13 @@ Some filters take arguments. A filter argument looks like this: ``{{
bio|truncatewords:30 }}``. This will display the first 30 words of the ``bio`` bio|truncatewords:30 }}``. This will display the first 30 words of the ``bio``
variable. variable.
Filter arguments that contain spaces must be quoted; for example, to join a list Filter arguments that contain spaces must be quoted; for example, to join a
with commas and spaced you'd use ``{{ list|join:", " }}``. list with commas and spaced you'd use ``{{ list|join:", " }}``.
Django provides about thirty built-in template filters. You can read all about Django provides about thirty built-in template filters. You can read all about
them in the :ref:`built-in filter reference <ref-templates-builtins-filters>`. them in the :ref:`built-in filter reference <ref-templates-builtins-filters>`.
To give you a taste of what's available, here are some of the more commonly used To give you a taste of what's available, here are some of the more commonly
template filters: used template filters:
:tfilter:`default` :tfilter:`default`
If a variable is false or empty, use given default. Otherwise, use the If a variable is false or empty, use given default. Otherwise, use the
@ -206,7 +206,7 @@ tags:
In the above, if ``athlete_list`` is not empty, the number of athletes In the above, if ``athlete_list`` is not empty, the number of athletes
will be displayed by the ``{{ athlete_list|length }}`` variable. will be displayed by the ``{{ athlete_list|length }}`` variable.
You can also use filters and various operators in the ``if`` tag:: You can also use filters and various operators in the :ttag:`if` tag::
{% if athlete_list|length > 1 %} {% if athlete_list|length > 1 %}
Team: {% for athlete in athlete_list %} ... {% endfor %} Team: {% for athlete in athlete_list %} ... {% endfor %}
@ -286,8 +286,8 @@ This template, which we'll call ``base.html``, defines a simple HTML skeleton
document that you might use for a simple two-column page. It's the job of document that you might use for a simple two-column page. It's the job of
"child" templates to fill the empty blocks with content. "child" templates to fill the empty blocks with content.
In this example, the ``{% block %}`` tag defines three blocks that child In this example, the :ttag:`block` tag defines three blocks that child
templates can fill in. All the ``block`` tag does is to tell the template templates can fill in. All the :ttag:`block` tag does is to tell the template
engine that a child template may override those portions of the template. engine that a child template may override those portions of the template.
A child template might look like this:: A child template might look like this::
@ -303,11 +303,11 @@ A child template might look like this::
{% endfor %} {% endfor %}
{% endblock %} {% endblock %}
The ``{% extends %}`` tag is the key here. It tells the template engine that The :ttag:`extends` tag is the key here. It tells the template engine that
this template "extends" another template. When the template system evaluates this template "extends" another template. When the template system evaluates
this template, first it locates the parent -- in this case, "base.html". this template, first it locates the parent -- in this case, "base.html".
At that point, the template engine will notice the three ``{% block %}`` tags At that point, the template engine will notice the three :ttag:`block` tags
in ``base.html`` and replace those blocks with the contents of the child in ``base.html`` and replace those blocks with the contents of the child
template. Depending on the value of ``blog_entries``, the output might look template. Depending on the value of ``blog_entries``, the output might look
like:: like::
@ -359,10 +359,10 @@ content areas, such as section-wide navigation.
Here are some tips for working with inheritance: Here are some tips for working with inheritance:
* If you use ``{% extends %}`` in a template, it must be the first template * If you use :ttag:`{% extends %}<extends>` in a template, it must be the first template
tag in that template. Template inheritance won't work, otherwise. tag in that template. Template inheritance won't work, otherwise.
* More ``{% block %}`` tags in your base templates are better. Remember, * More :ttag:`{% block %}<block>` tags in your base templates are better. Remember,
child templates don't have to define all parent blocks, so you can fill child templates don't have to define all parent blocks, so you can fill
in reasonable defaults in a number of blocks, then only define the ones in reasonable defaults in a number of blocks, then only define the ones
you need later. It's better to have more hooks than fewer hooks. you need later. It's better to have more hooks than fewer hooks.
@ -388,11 +388,11 @@ Here are some tips for working with inheritance:
In larger templates, this technique helps you see which ``{% block %}`` In larger templates, this technique helps you see which ``{% block %}``
tags are being closed. tags are being closed.
Finally, note that you can't define multiple ``{% block %}`` tags with the same Finally, note that you can't define multiple :ttag:`block` tags with the same
name in the same template. This limitation exists because a block tag works in name in the same template. This limitation exists because a block tag works in
"both" directions. That is, a block tag doesn't just provide a hole to fill -- "both" directions. That is, a block tag doesn't just provide a hole to fill --
it also defines the content that fills the hole in the *parent*. If there were it also defines the content that fills the hole in the *parent*. If there were
two similarly-named ``{% block %}`` tags in a template, that template's parent two similarly-named :ttag:`block` tags in a template, that template's parent
wouldn't know which one of the blocks' content to use. wouldn't know which one of the blocks' content to use.
.. _next section: #automatic-html-escaping .. _next section: #automatic-html-escaping
@ -436,8 +436,8 @@ do potentially bad things. This type of security exploit is called a
To avoid this problem, you have two options: To avoid this problem, you have two options:
* One, you can make sure to run each untrusted variable through the * One, you can make sure to run each untrusted variable through the
``escape`` filter (documented below), which converts potentially harmful :tfilter:`escape` filter (documented below), which converts potentially
HTML characters to unharmful ones. This was the default solution harmful HTML characters to unharmful ones. This was the default solution
in Django for its first few years, but the problem is that it puts the in Django for its first few years, but the problem is that it puts the
onus on *you*, the developer / template author, to ensure you're escaping onus on *you*, the developer / template author, to ensure you're escaping
everything. It's easy to forget to escape data. everything. It's easy to forget to escape data.
@ -476,7 +476,8 @@ you might be using Django's template system to produce text that is *not* HTML
For individual variables For individual variables
~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~
To disable auto-escaping for an individual variable, use the ``safe`` filter:: To disable auto-escaping for an individual variable, use the :tfilter:`safe`
filter::
This will be escaped: {{ data }} This will be escaped: {{ data }}
This will not be escaped: {{ data|safe }} This will not be escaped: {{ data|safe }}
@ -492,13 +493,13 @@ For template blocks
~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~
To control auto-escaping for a template, wrap the template (or just a To control auto-escaping for a template, wrap the template (or just a
particular section of the template) in the ``autoescape`` tag, like so:: particular section of the template) in the :ttag:`autoescape` tag, like so::
{% autoescape off %} {% autoescape off %}
Hello {{ name }} Hello {{ name }}
{% endautoescape %} {% endautoescape %}
The ``autoescape`` tag takes either ``on`` or ``off`` as its argument. At The :ttag:`autoescape` tag takes either ``on`` or ``off`` as its argument. At
times, you might want to force auto-escaping when it would otherwise be times, you might want to force auto-escaping when it would otherwise be
disabled. Here is an example template:: disabled. Here is an example template::
@ -514,8 +515,8 @@ disabled. Here is an example template::
{% endautoescape %} {% endautoescape %}
The auto-escaping tag passes its effect onto templates that extend the The auto-escaping tag passes its effect onto templates that extend the
current one as well as templates included via the ``include`` tag, just like current one as well as templates included via the :ttag:`include` tag,
all block tags. For example:: just like all block tags. For example::
# base.html # base.html
@ -548,10 +549,10 @@ think about the cases in which data shouldn't be escaped, and mark data
appropriately, so things Just Work in the template. appropriately, so things Just Work in the template.
If you're creating a template that might be used in situations where you're If you're creating a template that might be used in situations where you're
not sure whether auto-escaping is enabled, then add an ``escape`` filter to any not sure whether auto-escaping is enabled, then add an :tfilter:`escape` filter
variable that needs escaping. When auto-escaping is on, there's no danger of to any variable that needs escaping. When auto-escaping is on, there's no
the ``escape`` filter *double-escaping* data -- the ``escape`` filter does not danger of the :tfilter:`escape` filter *double-escaping* data -- the
affect auto-escaped variables. :tfilter:`escape` filter does not affect auto-escaped variables.
String literals and automatic escaping String literals and automatic escaping
-------------------------------------- --------------------------------------
@ -561,9 +562,9 @@ As we mentioned earlier, filter arguments can be strings::
{{ data|default:"This is a string literal." }} {{ data|default:"This is a string literal." }}
All string literals are inserted **without** any automatic escaping into the All string literals are inserted **without** any automatic escaping into the
template -- they act as if they were all passed through the ``safe`` filter. template -- they act as if they were all passed through the :tfilter:`safe`
The reasoning behind this is that the template author is in control of what filter. The reasoning behind this is that the template author is in control of
goes into the string literal, so they can make sure the text is correctly what goes into the string literal, so they can make sure the text is correctly
escaped when the template is written. escaped when the template is written.
This means you would write :: This means you would write ::