summaryrefslogtreecommitdiff
path: root/docs/ref/templates
diff options
context:
space:
mode:
authorCarlton Gibson <carlton.gibson@noumenal.es>2023-02-09 16:48:46 +0100
committerMariusz Felisiak <felisiak.mariusz@gmail.com>2023-02-10 19:19:13 +0100
commit534ac4829764f317cf2fbc4a18354fcc998c1425 (patch)
treec85c1df220ea6c3a87f9820106ba5a06e9ec9394 /docs/ref/templates
parent7bb741d787ba360a9f0d490db92e22e0d28204ed (diff)
downloaddjango-534ac4829764f317cf2fbc4a18354fcc998c1425.tar.gz
Refs #34140 -- Applied rst code-block to non-Python examples.
Thanks to J.V. Zammit, Paolo Melchiorre, and Mariusz Felisiak for reviews.
Diffstat (limited to 'docs/ref/templates')
-rw-r--r--docs/ref/templates/api.txt38
-rw-r--r--docs/ref/templates/builtins.txt626
-rw-r--r--docs/ref/templates/language.txt126
3 files changed, 589 insertions, 201 deletions
diff --git a/docs/ref/templates/api.txt b/docs/ref/templates/api.txt
index 8110d5bed9..e080388ff4 100644
--- a/docs/ref/templates/api.txt
+++ b/docs/ref/templates/api.txt
@@ -211,7 +211,9 @@ different contexts.
.. method:: Template.render(context)
Call the :class:`Template` object's ``render()`` method with a
- :class:`Context` to "fill" the template::
+ :class:`Context` to "fill" the template:
+
+ .. code-block:: pycon
>>> from django.template import Context, Template
>>> template = Template("My name is {{ my_name }}.")
@@ -243,7 +245,9 @@ interpreted as a literal string and not using the value of the variable "bar",
if one exists in the template context.
The template system uses the first lookup type that works. It's short-circuit
-logic. Here are a few examples::
+logic. Here are a few examples:
+
+.. code-block:: pycon
>>> from django.template import Context, Template
>>> t = Template("My name is {{ person.first_name }}.")
@@ -264,7 +268,9 @@ logic. Here are a few examples::
"The first stooge in the list is Larry."
If any part of the variable is callable, the template system will try calling
-it. Example::
+it. Example:
+
+.. code-block:: pycon
>>> class PersonClass2:
... def name(self):
@@ -282,7 +288,9 @@ straight lookups. Here are some things to keep in mind:
*does* have a ``silent_variable_failure`` attribute whose value is
``True``, the variable will render as the value of the engine's
``string_if_invalid`` configuration option (an empty string, by default).
- Example::
+ Example:
+
+ .. code-block:: pycon
>>> t = Template("My name is {{ person.first_name }}.")
>>> class PersonClass3:
@@ -320,9 +328,11 @@ straight lookups. Here are some things to keep in mind:
A good example is the :meth:`~django.db.models.Model.delete` method on
each Django model object. The template system shouldn't be allowed to do
- something like this::
+ something like this:
+
+ .. code-block:: html+django
- I will now delete this valuable data. {{ data.delete }}
+ I will now delete this valuable data. {{ data.delete }}
To prevent this, set an ``alters_data`` attribute on the callable
variable. The template system won't call a variable if it has
@@ -395,14 +405,18 @@ A similar issue exists if you want to include these sequences in template filter
or tag arguments. For example, when parsing a block tag, Django's template
parser looks for the first occurrence of ``%}`` after a ``{%``. This prevents
the use of ``"%}"`` as a string literal. For example, a ``TemplateSyntaxError``
-will be raised for the following expressions::
+will be raised for the following expressions:
+
+.. code-block:: html+django
{% include "template.html" tvar="Some string literal with %} in it." %}
{% with tvar="Some string literal with %} in it." %}{% endwith %}
The same issue can be triggered by using a reserved sequence in filter
-arguments::
+arguments:
+
+.. code-block:: html+django
{{ some.variable|default:"}}" }}
@@ -417,7 +431,9 @@ Playing with ``Context`` objects
Most of the time, you'll instantiate :class:`Context` objects by passing in a
fully-populated dictionary to ``Context()``. But you can add and delete items
from a ``Context`` object once it's been instantiated, too, using standard
-dictionary syntax::
+dictionary syntax:
+
+.. code-block:: pycon
>>> from django.template import Context
>>> c = Context({"foo": "bar"})
@@ -448,7 +464,9 @@ dictionary syntax::
A ``Context`` object is a stack. That is, you can ``push()`` and ``pop()`` it.
If you ``pop()`` too much, it'll raise
-``django.template.ContextPopException``::
+``django.template.ContextPopException``:
+
+.. code-block:: pycon
>>> c = Context()
>>> c['foo'] = 'first level'
diff --git a/docs/ref/templates/builtins.txt b/docs/ref/templates/builtins.txt
index f866e865b5..d69bd3266a 100644
--- a/docs/ref/templates/builtins.txt
+++ b/docs/ref/templates/builtins.txt
@@ -12,8 +12,6 @@ documentation for any custom tags or filters installed.
Built-in tag reference
======================
-.. highlight:: html+django
-
.. templatetag:: autoescape
``autoescape``
@@ -32,7 +30,9 @@ 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
the :tfilter:`safe` or :tfilter:`escape` filters applied.
-Sample usage::
+Sample usage:
+
+.. code-block:: html+django
{% autoescape on %}
{{ body }}
@@ -55,7 +55,9 @@ Ignores everything between ``{% comment %}`` and ``{% endcomment %}``.
An optional note may be inserted in the first tag. For example, this is
useful when commenting out code for documenting why the code was disabled.
-Sample usage::
+Sample usage:
+
+.. code-block:: html+django
<p>Rendered text with {{ pub_date|date:"c" }}</p>
{% comment "Optional note" %}
@@ -82,7 +84,9 @@ argument is produced on the first encounter, the second argument on the second
encounter, and so forth. Once all arguments are exhausted, the tag cycles to
the first argument and produces it again.
-This tag is particularly useful in a loop::
+This tag is particularly useful in a loop:
+
+.. code-block:: html+django
{% for o in some_list %}
<tr class="{% cycle 'row1' 'row2' %}">
@@ -96,7 +100,9 @@ loop.
You can use variables, too. For example, if you have two template variables,
``rowvalue1`` and ``rowvalue2``, you can alternate between their values like
-this::
+this:
+
+.. code-block:: html+django
{% for o in some_list %}
<tr class="{% cycle rowvalue1 rowvalue2 %}">
@@ -105,7 +111,9 @@ this::
{% endfor %}
Variables included in the cycle will be escaped. You can disable auto-escaping
-with::
+with:
+
+.. code-block:: html+django
{% for o in some_list %}
<tr class="{% autoescape off %}{% cycle rowvalue1 rowvalue2 %}{% endautoescape %}">
@@ -113,7 +121,9 @@ with::
</tr>
{% endfor %}
-You can mix variables and strings::
+You can mix variables and strings:
+
+.. code-block:: html+django
{% for o in some_list %}
<tr class="{% cycle 'row1' rowvalue2 'row3' %}">
@@ -123,7 +133,9 @@ You can mix variables and strings::
In some cases you might want to refer to the current value of a cycle
without advancing to the next value. To do this,
-give the ``{% cycle %}`` tag a name, using "as", like this::
+give the ``{% cycle %}`` tag a name, using "as", like this:
+
+.. code-block:: html+django
{% cycle 'row1' 'row2' as rowcolors %}
@@ -131,7 +143,9 @@ From then on, you can insert the current value of the cycle wherever you'd like
in your template by referencing the cycle name as a context variable. If you
want to move the cycle to the next value independently of the original
``cycle`` tag, you can use another ``cycle`` tag and specify the name of the
-variable. So, the following template::
+variable. So, the following template:
+
+.. code-block:: html+django
<tr>
<td class="{% cycle 'row1' 'row2' as rowcolors %}">...</td>
@@ -142,7 +156,9 @@ variable. So, the following template::
<td class="{{ rowcolors }}">...</td>
</tr>
-would output::
+would output:
+
+.. code-block:: html+django
<tr>
<td class="row1">...</td>
@@ -163,7 +179,9 @@ usage of ``{% cycle %}`` that initiates the cycle will itself produce
the first value in the cycle. This could be a problem if you want to
use the value in a nested loop or an included template. If you only want
to declare the cycle but not produce the first value, you can add a
-``silent`` keyword as the last keyword in the tag. For example::
+``silent`` keyword as the last keyword in the tag. For example:
+
+.. code-block:: html+django
{% for obj in some_list %}
{% cycle 'row1' 'row2' as rowcolors silent %}
@@ -180,7 +198,9 @@ omitted, ``row1`` and ``row2`` would be emitted as normal text, outside the
When the silent keyword is used on a cycle definition, the silence
automatically applies to all subsequent uses of that specific cycle tag.
The following template would output *nothing*, even though the second
-call to ``{% cycle %}`` doesn't specify ``silent``::
+call to ``{% cycle %}`` doesn't specify ``silent``:
+
+.. code-block:: html+django
{% cycle 'row1' 'row2' as rowcolors silent %}
{% cycle rowcolors %}
@@ -223,7 +243,9 @@ See :ref:`template-inheritance` for more information.
Normally the template name is relative to the template loader's root directory.
A string argument may also be a relative path starting with ``./`` or ``../``.
-For example, assume the following directory structure::
+For example, assume the following directory structure:
+
+.. code-block:: text
dir1/
template.html
@@ -232,7 +254,9 @@ For example, assume the following directory structure::
base3.html
base1.html
-In ``template.html``, the following paths would be valid::
+In ``template.html``, the following paths would be valid:
+
+.. code-block:: html+django
{% extends "./base2.html" %}
{% extends "../base1.html" %}
@@ -250,7 +274,9 @@ in variable syntax.
Note that the block includes *all* the text between the ``filter`` and
``endfilter`` tags.
-Sample usage::
+Sample usage:
+
+.. code-block:: html+django
{% filter force_escape|lower %}
This text will be HTML-escaped, and will appear in all lowercase.
@@ -271,11 +297,15 @@ Outputs the first argument variable that is not "false" (i.e. exists, is not
empty, is not a false boolean value, and is not a zero numeric value). Outputs
nothing if all the passed variables are "false".
-Sample usage::
+Sample usage:
+
+.. code-block:: html+django
{% firstof var1 var2 var3 %}
-This is equivalent to::
+This is equivalent to:
+
+.. code-block:: html+django
{% if var1 %}
{{ var1 }}
@@ -286,17 +316,23 @@ This is equivalent to::
{% endif %}
You can also use a literal string as a fallback value in case all
-passed variables are False::
+passed variables are False:
+
+.. code-block:: html+django
{% firstof var1 var2 var3 "fallback value" %}
-This tag auto-escapes variable values. You can disable auto-escaping with::
+This tag auto-escapes variable values. You can disable auto-escaping with:
+
+.. code-block:: html+django
{% autoescape off %}
{% firstof var1 var2 var3 "<strong>fallback value</strong>" %}
{% endautoescape %}
-Or if only some variables should be escaped, you can use::
+Or if only some variables should be escaped, you can use:
+
+.. code-block:: html+django
{% firstof var1 var2|safe var3 "<strong>fallback value</strong>"|safe %}
@@ -310,7 +346,9 @@ output inside a variable.
Loops over each item in an array, making the item available in a context
variable. For example, to display a list of athletes provided in
-``athlete_list``::
+``athlete_list``:
+
+.. code-block:: html+django
<ul>
{% for athlete in athlete_list %}
@@ -324,7 +362,9 @@ You can loop over a list in reverse by using
If you need to loop over a list of lists, you can unpack the values
in each sublist into individual variables. For example, if your context
contains a list of (x,y) coordinates called ``points``, you could use the
-following to output the list of points::
+following to output the list of points:
+
+.. code-block:: html+django
{% for x, y in points %}
There is a point at {{ x }},{{ y }}
@@ -332,7 +372,9 @@ following to output the list of points::
This can also be useful if you need to access the items in a dictionary.
For example, if your context contained a dictionary ``data``, the following
-would display the keys and values of the dictionary::
+would display the keys and values of the dictionary:
+
+.. code-block:: html+django
{% for key, value in data.items %}
{{ key }}: {{ value }}
@@ -367,7 +409,9 @@ Variable Description
---------------------
The ``for`` tag can take an optional ``{% empty %}`` clause whose text is
-displayed if the given array is empty or could not be found::
+displayed if the given array is empty or could not be found:
+
+.. code-block:: html+django
<ul>
{% for athlete in athlete_list %}
@@ -378,7 +422,9 @@ displayed if the given array is empty or could not be found::
</ul>
The above is equivalent to -- but shorter, cleaner, and possibly faster
-than -- the following::
+than -- the following:
+
+.. code-block:: html+django
<ul>
{% if athlete_list %}
@@ -397,7 +443,9 @@ than -- the following::
The ``{% if %}`` tag evaluates a variable, and if that variable is "true" (i.e.
exists, is not empty, and is not a false boolean value) the contents of the
-block are output::
+block are output:
+
+.. code-block:: html+django
{% if athlete_list %}
Number of athletes: {{ athlete_list|length }}
@@ -418,7 +466,9 @@ Boolean operators
~~~~~~~~~~~~~~~~~
:ttag:`if` tags may use ``and``, ``or`` or ``not`` to test a number of
-variables or to negate a given variable::
+variables or to negate a given variable:
+
+.. code-block:: html+django
{% if athlete_list and coach_list %}
Both athletes and coaches are available.
@@ -441,7 +491,9 @@ variables or to negate a given variable::
{% endif %}
Use of both ``and`` and ``or`` clauses within the same tag is allowed, with
-``and`` having higher precedence than ``or`` e.g.::
+``and`` having higher precedence than ``or`` e.g.:
+
+.. code-block:: html+django
{% if athlete_list and coach_list or cheerleader_list %}
@@ -461,7 +513,9 @@ follows:
``==`` operator
^^^^^^^^^^^^^^^
-Equality. Example::
+Equality. Example:
+
+.. code-block:: html+django
{% if somevar == "x" %}
This appears if variable somevar equals the string "x"
@@ -470,7 +524,9 @@ Equality. Example::
``!=`` operator
^^^^^^^^^^^^^^^
-Inequality. Example::
+Inequality. Example:
+
+.. code-block:: html+django
{% if somevar != "x" %}
This appears if variable somevar does not equal the string "x",
@@ -480,7 +536,9 @@ Inequality. Example::
``<`` operator
^^^^^^^^^^^^^^
-Less than. Example::
+Less than. Example:
+
+.. code-block:: html+django
{% if somevar < 100 %}
This appears if variable somevar is less than 100.
@@ -489,7 +547,9 @@ Less than. Example::
``>`` operator
^^^^^^^^^^^^^^
-Greater than. Example::
+Greater than. Example:
+
+.. code-block:: html+django
{% if somevar > 0 %}
This appears if variable somevar is greater than 0.
@@ -498,7 +558,9 @@ Greater than. Example::
``<=`` operator
^^^^^^^^^^^^^^^
-Less than or equal to. Example::
+Less than or equal to. Example:
+
+.. code-block:: html+django
{% if somevar <= 100 %}
This appears if variable somevar is less than 100 or equal to 100.
@@ -507,7 +569,9 @@ Less than or equal to. Example::
``>=`` operator
^^^^^^^^^^^^^^^
-Greater than or equal to. Example::
+Greater than or equal to. Example:
+
+.. code-block:: html+django
{% if somevar >= 1 %}
This appears if variable somevar is greater than 1 or equal to 1.
@@ -518,7 +582,9 @@ Greater than or equal to. Example::
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 how ``x in y`` will be interpreted::
+of how ``x in y`` will be interpreted:
+
+.. code-block:: html+django
{% if "bc" in "abcdef" %}
This appears since "bc" is a substring of "abcdef"
@@ -542,7 +608,9 @@ Not contained within. This is the negation of the ``in`` operator.
``is`` operator
^^^^^^^^^^^^^^^
-Object identity. Tests if two values are the same object. Example::
+Object identity. Tests if two values are the same object. Example:
+
+.. code-block:: html+django
{% if somevar is True %}
This appears if and only if somevar is True.
@@ -556,7 +624,9 @@ Object identity. Tests if two values are the same object. Example::
^^^^^^^^^^^^^^^^^^^
Negated object identity. Tests if two values are not the same object. This is
-the negation of the ``is`` operator. Example::
+the negation of the ``is`` operator. Example:
+
+.. code-block:: html+django
{% if somevar is not True %}
This appears if somevar is not True, or if somevar is not found in the
@@ -570,7 +640,9 @@ the negation of the ``is`` operator. Example::
Filters
~~~~~~~
-You can also use filters in the :ttag:`if` expression. For example::
+You can also use filters in the :ttag:`if` expression. For example:
+
+.. code-block:: html+django
{% if messages|length >= 100 %}
You have lots of messages today!
@@ -591,7 +663,9 @@ operators, from lowest to highest, is as follows:
* ``==``, ``!=``, ``<``, ``>``, ``<=``, ``>=``
(This follows Python exactly). So, for example, the following complex
-:ttag:`if` tag::
+:ttag:`if` tag:
+
+.. code-block:: html+django
{% if a == b or c == d and e %}
@@ -606,11 +680,15 @@ Sometimes that is better for clarity anyway, for the sake of those who do not
know the precedence rules.
The comparison operators cannot be 'chained' like in Python or in mathematical
-notation. For example, instead of using::
+notation. For example, instead of using:
+
+.. code-block:: html+django
{% if a > b > c %} (WRONG)
-you should use::
+you should use:
+
+.. code-block:: html+django
{% if a > b and b > c %}
@@ -626,7 +704,9 @@ uses.
1. Checks its own rendered contents against its previous state and only
displays the content if it has changed. For example, this displays a list of
- days, only displaying the month if it changes::
+ days, only displaying the month if it changes:
+
+ .. code-block:: html+django
<h1>Archive for {{ year }}</h1>
@@ -637,7 +717,9 @@ uses.
2. If given one or more variables, check whether any variable has changed.
For example, the following shows the date every time it changes, while
- showing the hour if either the hour or the date has changed::
+ showing the hour if either the hour or the date has changed:
+
+ .. code-block:: html+django
{% for date in days %}
{% ifchanged date.date %} {{ date.date }} {% endifchanged %}
@@ -647,7 +729,9 @@ uses.
{% endfor %}
The ``ifchanged`` tag can also take an optional ``{% else %}`` clause that
-will be displayed if the value has not changed::
+will be displayed if the value has not changed:
+
+.. code-block:: html+django
{% for match in matches %}
<div style="background-color:
@@ -670,7 +754,9 @@ Loads a template and renders it with the current context. This is a way of
The template name can either be a variable or a hard-coded (quoted) string,
in either single or double quotes.
-This example includes the contents of the template ``"foo/bar.html"``::
+This example includes the contents of the template ``"foo/bar.html"``:
+
+.. code-block:: html+django
{% include "foo/bar.html" %}
@@ -679,7 +765,9 @@ A string argument may also be a relative path starting with ``./`` or ``../``
as described in the :ttag:`extends` tag.
This example includes the contents of the template whose name is contained in
-the variable ``template_name``::
+the variable ``template_name``:
+
+.. code-block:: html+django
{% include template_name %}
@@ -696,21 +784,29 @@ includes it. This example produces the output ``"Hello, John!"``:
* Context: variable ``person`` is set to ``"John"`` and variable ``greeting``
is set to ``"Hello"``.
-* Template::
+* Template:
+
+ .. code-block:: html+django
{% include "name_snippet.html" %}
-* The ``name_snippet.html`` template::
+* The ``name_snippet.html`` template:
+
+ .. code-block:: html+django
{{ greeting }}, {{ person|default:"friend" }}!
-You can pass additional context to the template using keyword arguments::
+You can pass additional context to the template using keyword arguments:
+
+.. code-block:: html+django
{% include "name_snippet.html" with person="Jane" greeting="Hello" %}
If you want to render the context only with the variables provided (or even
no variables at all), use the ``only`` option. No other variables are
-available to the included template::
+available to the included template:
+
+.. code-block:: html+django
{% include "name_snippet.html" with greeting="Hi" only %}
@@ -735,13 +831,17 @@ Loads a custom template tag set.
For example, the following template would load all the tags and filters
registered in ``somelibrary`` and ``otherlibrary`` located in package
-``package``::
+``package``:
+
+.. code-block:: html+django
{% load somelibrary package.otherlibrary %}
You can also selectively load individual filters or tags from a library, using
the ``from`` argument. In this example, the template tags/filters named ``foo``
-and ``bar`` will be loaded from ``somelibrary``::
+and ``bar`` will be loaded from ``somelibrary``:
+
+.. code-block:: html+django
{% load foo bar from somelibrary %}
@@ -756,7 +856,9 @@ more information.
Displays random "lorem ipsum" Latin text. This is useful for providing sample
data in templates.
-Usage::
+Usage:
+
+.. code-block:: html+django
{% lorem [count] [method] [random] %}
@@ -791,14 +893,18 @@ Displays the current date and/or time, using a format according to the given
string. Such string can contain format specifiers characters as described
in the :tfilter:`date` filter section.
-Example::
+Example:
+
+.. code-block:: html+django
It is {% now "jS F Y H:i" %}
Note that you can backslash-escape a format string if you want to use the
"raw" value. In this example, both "o" and "f" are backslash-escaped, because
otherwise each is a format string that displays the year and the time,
-respectively::
+respectively:
+
+.. code-block:: html+django
It is the {% now "jS \o\f F" %}
@@ -810,13 +916,17 @@ This would display as "It is the 4th of September".
:setting:`DATE_FORMAT`, :setting:`DATETIME_FORMAT`,
:setting:`SHORT_DATE_FORMAT` or :setting:`SHORT_DATETIME_FORMAT`.
The predefined formats may vary depending on the current locale and
- if :doc:`/topics/i18n/formatting` is enabled, e.g.::
+ if :doc:`/topics/i18n/formatting` is enabled, e.g.:
+
+ .. code-block:: html+django
It is {% now "SHORT_DATETIME_FORMAT" %}
You can also use the syntax ``{% now "Y" as current_year %}`` to store the
output (as a string) inside a variable. This is useful if you want to use
-``{% now %}`` inside a template tag like :ttag:`blocktranslate` for example::
+``{% now %}`` inside a template tag like :ttag:`blocktranslate` for example:
+
+.. code-block:: html+django
{% now "Y" as current_year %}
{% blocktranslate %}Copyright {{ current_year }}{% endblocktranslate %}
@@ -860,7 +970,9 @@ like this:
* Tokyo: 33,000,000
You can use the ``{% regroup %}`` tag to group the list of cities by country.
-The following snippet of template code would accomplish this::
+The following snippet of template code would accomplish this:
+
+.. code-block:: html+django
{% regroup cities by country as country_list %}
@@ -891,7 +1003,9 @@ attribute and calling the result ``country_list``.
with country='India').
Because ``{% regroup %}`` produces :py:func:`~collections.namedtuple` objects,
-you can also write the previous example as::
+you can also write the previous example as:
+
+.. code-block:: html+django
{% regroup cities by country as country_list %}
@@ -951,7 +1065,9 @@ 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.
Another solution is to sort the data in the template using the
-:tfilter:`dictsort` filter, if your data is in a list of dictionaries::
+:tfilter:`dictsort` filter, if your data is in a list of dictionaries:
+
+.. code-block:: html+django
{% regroup cities|dictsort:"country" by country as country_list %}
@@ -961,14 +1077,18 @@ Grouping on other properties
Any valid template lookup is a legal grouping attribute for the regroup
tag, including methods, attributes, dictionary keys and list items. For
example, if the "country" field is a foreign key to a class with
-an attribute "description," you could use::
+an attribute "description," you could use:
+
+.. code-block:: html+django
{% regroup cities by country.description as country_list %}
Or, if ``country`` is a field with ``choices``, it will have a
:meth:`~django.db.models.Model.get_FOO_display` method available as an
attribute, allowing you to group on the display string rather than the
-``choices`` key::
+``choices`` key:
+
+.. code-block:: html+django
{% regroup cities by get_country_display as country_list %}
@@ -984,7 +1104,9 @@ Resets a previous `cycle`_ so that it restarts from its first item at its next
encounter. Without arguments, ``{% resetcycle %}`` will reset the last
``{% cycle %}`` defined in the template.
-Example usage::
+Example usage:
+
+.. code-block:: html+django
{% for coach in coach_list %}
<h1>{{ coach.name }}</h1>
@@ -1009,7 +1131,9 @@ Notice how the first block ends with ``class="odd"`` and the new one starts
with ``class="odd"``. Without the ``{% resetcycle %}`` tag, the second block
would start with ``class="even"``.
-You can also reset named cycle tags::
+You can also reset named cycle tags:
+
+.. code-block:: html+django
{% for item in list %}
<p class="{% cycle 'odd' 'even' as stripe %} {% cycle 'major' 'minor' 'minor' 'minor' 'minor' as tick %}">
@@ -1032,7 +1156,9 @@ every fifth row. Only the five-row cycle is reset when a category changes.
Removes whitespace between HTML tags. This includes tab
characters and newlines.
-Example usage::
+Example usage:
+
+.. code-block:: html+django
{% spaceless %}
<p>
@@ -1040,12 +1166,16 @@ Example usage::
</p>
{% endspaceless %}
-This example would return this HTML::
+This example would return this HTML:
+
+.. code-block:: html+django
<p><a href="foo/">Foo</a></p>
Only space between *tags* is removed -- not space between tags and text. In
-this example, the space around ``Hello`` won't be stripped::
+this example, the space around ``Hello`` won't be stripped:
+
+.. code-block:: html+django
{% spaceless %}
<strong>
@@ -1079,7 +1209,9 @@ Argument Outputs
``closecomment`` ``#}``
================== =======
-Sample usage::
+Sample usage:
+
+.. code-block:: html+django
The {% templatetag openblock %} characters open a block.
@@ -1096,7 +1228,9 @@ given view and optional parameters. Any special characters in the resulting
path will be encoded using :func:`~django.utils.encoding.iri_to_uri`.
This is a way to output links without violating the DRY principle by having to
-hard-code URLs in your templates::
+hard-code URLs in your templates:
+
+.. code-block:: html+django
{% url 'some-url-name' v1 v2 %}
@@ -1104,7 +1238,9 @@ The first argument is a :ref:`URL pattern name <naming-url-patterns>`. It can
be a quoted literal or any other context variable. Additional arguments are
optional and should be space-separated values that will be used as arguments in
the URL. The example above shows passing positional arguments. Alternatively
-you may use keyword syntax::
+you may use keyword syntax:
+
+.. code-block:: html+django
{% url 'some-url-name' arg1=v1 arg2=v2 %}
@@ -1137,7 +1273,9 @@ Note that if the URL you're reversing doesn't exist, you'll get an
site to display an error page.
If you'd like to retrieve a URL without displaying it, you can use a slightly
-different call::
+different call:
+
+.. code-block:: html+django
{% url 'some-url-name' arg arg2 as the_url %}
@@ -1147,14 +1285,18 @@ The scope of the variable created by the ``as var`` syntax is the
``{% block %}`` in which the ``{% url %}`` tag appears.
This ``{% url ... as var %}`` syntax will *not* cause an error if the view is
-missing. In practice you'll use this to link to views that are optional::
+missing. In practice you'll use this to link to views that are optional:
+
+.. code-block:: html+django
{% url 'some-url-name' as the_url %}
{% if the_url %}
<a href="{{ the_url }}">Link to optional stuff</a>
{% endif %}
-If you'd like to retrieve a namespaced URL, specify the fully qualified name::
+If you'd like to retrieve a namespaced URL, specify the fully qualified name:
+
+.. code-block:: html+django
{% url 'myapp:view-name' %}
@@ -1175,14 +1317,18 @@ by the context as to the current application.
Stops the template engine from rendering the contents of this block tag.
A common use is to allow a JavaScript template layer that collides with
-Django's syntax. For example::
+Django's syntax. For example:
+
+.. code-block:: html+django
{% verbatim %}
{{if dying}}Still alive.{{/if}}
{% endverbatim %}
You can also designate a specific closing tag, allowing the use of
-``{% endverbatim %}`` as part of the unrendered contents::
+``{% endverbatim %}`` as part of the unrendered contents:
+
+.. code-block:: html+django
{% verbatim myblock %}
Avoid template rendering via the {% verbatim %}{% endverbatim %} block.
@@ -1196,7 +1342,9 @@ You can also designate a specific closing tag, allowing the use of
For creating bar charts and such, this tag calculates the ratio of a given
value to a maximum value, and then applies that ratio to a constant.
-For example::
+For example:
+
+.. code-block:: html+django
<img src="bar.png" alt="Bar"
height="10" width="{% widthratio this_value max_value max_width %}">
@@ -1206,7 +1354,9 @@ image in the above example will be 88 pixels wide
(because 175/200 = .875; .875 * 100 = 87.5 which is rounded up to 88).
In some cases you might want to capture the result of ``widthratio`` in a
-variable. It can be useful, for instance, in a :ttag:`blocktranslate` like this::
+variable. It can be useful, for instance, in a :ttag:`blocktranslate` like this:
+
+.. code-block:: html+django
{% widthratio this_value max_value max_width as width %}
{% blocktranslate %}The width is: {{ width }}{% endblocktranslate %}
@@ -1219,7 +1369,9 @@ variable. It can be useful, for instance, in a :ttag:`blocktranslate` like this:
Caches a complex variable under a simpler name. This is useful when accessing
an "expensive" method (e.g., one that hits the database) multiple times.
-For example::
+For example:
+
+.. code-block:: html+django
{% with total=business.employees.count %}
{{ total }} employee{{ total|pluralize }}
@@ -1228,7 +1380,9 @@ For example::
The populated variable (in the example above, ``total``) is only available
between the ``{% with %}`` and ``{% endwith %}`` tags.
-You can assign more than one context variable::
+You can assign more than one context variable:
+
+.. code-block:: html+django
{% with alpha=1 beta=2 %}
...
@@ -1249,7 +1403,9 @@ Built-in filter reference
Adds the argument to the value.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|add:"2" }}
@@ -1260,7 +1416,9 @@ it'll attempt to add the values together anyway. This will work on some data
types (strings, list, etc.) and fail on others. If it fails, the result will
be an empty string.
-For example, if we have::
+For example, if we have:
+
+.. code-block:: html+django
{{ first|add:second }}
@@ -1279,7 +1437,9 @@ output will be ``[1, 2, 3, 4, 5, 6]``.
Adds slashes before quotes. Useful for escaping strings in CSV, for example.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|addslashes }}
@@ -1294,7 +1454,9 @@ If ``value`` is ``"I'm using Django"``, the output will be
Capitalizes the first character of the value. If the first character is not
a letter, this filter has no effect.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|capfirst }}
@@ -1307,7 +1469,9 @@ If ``value`` is ``"django"``, the output will be ``"Django"``.
Centers the value in a field of a given width.
-For example::
+For example:
+
+.. code-block:: html+django
"{{ value|center:"15" }}"
@@ -1320,7 +1484,9 @@ If ``value`` is ``"Django"``, the output will be ``" Django "``.
Removes all values of arg from the given string.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|cut:" " }}
@@ -1431,7 +1597,9 @@ Format character Description Example output
(January 1 1970 00:00:00 UTC).
================ ======================================== =====================
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|date:"D d M Y" }}
@@ -1445,7 +1613,9 @@ The format passed can be one of the predefined ones :setting:`DATE_FORMAT`,
specifiers shown in the table above. Note that predefined formats may vary
depending on the current locale.
-Assuming that :setting:`LANGUAGE_CODE` is, for example, ``"es"``, then for::
+Assuming that :setting:`LANGUAGE_CODE` is, for example, ``"es"``, then for:
+
+.. code-block:: html+django
{{ value|date:"SHORT_DATE_FORMAT" }}
@@ -1453,7 +1623,9 @@ the output would be the string ``"09/01/2008"`` (the ``"SHORT_DATE_FORMAT"``
format specifier for the ``es`` locale as shipped with Django is ``"d/m/Y"``).
When used without a format string, the ``DATE_FORMAT`` format specifier is
-used. Assuming the same settings as the previous example::
+used. Assuming the same settings as the previous example:
+
+.. code-block:: html+django
{{ value|date }}
@@ -1463,7 +1635,9 @@ backslash-escaped, because otherwise each is a format string that displays the
day and the timezone name, respectively.
You can combine ``date`` with the :tfilter:`time` filter to render a full
-representation of a ``datetime`` value. E.g.::
+representation of a ``datetime`` value. E.g.:
+
+.. code-block:: html+django
{{ value|date:"D d M Y" }} {{ value|time:"H:i" }}
@@ -1475,7 +1649,9 @@ representation of a ``datetime`` value. E.g.::
If value evaluates to ``False``, uses the given default. Otherwise, uses the
value.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|default:"nothing" }}
@@ -1492,7 +1668,9 @@ value.
Note that if an empty string is given, the default value will *not* be used.
Use the :tfilter:`default` filter if you want to fallback for empty strings.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|default_if_none:"nothing" }}
@@ -1506,7 +1684,9 @@ If ``value`` is ``None``, the output will be ``nothing``.
Takes a list of dictionaries and returns that list sorted by the key given in
the argument.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|dictsort:"name" }}
@@ -1530,7 +1710,9 @@ then the output would be:
{'name': 'zed', 'age': 19},
]
-You can also do more complicated things like::
+You can also do more complicated things like:
+
+.. code-block:: html+django
{% for book in books|dictsort:"author.age" %}
* {{ book.title }} ({{ book.author.name }})
@@ -1546,14 +1728,18 @@ If ``books`` is:
{'title': 'Alice', 'author': {'name': 'Lewis', 'age': 33}},
]
-then the output would be::
+then the output would be:
+
+.. code-block:: html+django
* Alice (Lewis)
* 1984 (George)
* Timequake (Kurt)
``dictsort`` can also order a list of lists (or any other object implementing
-``__getitem__()``) by elements at specified index. For example::
+``__getitem__()``) by elements at specified index. For example:
+
+.. code-block:: html+django
{{ value|dictsort:0 }}
@@ -1578,7 +1764,9 @@ then the output would be:
]
You must pass the index as an integer rather than a string. The following
-produce empty output::
+produce empty output:
+
+.. code-block:: html+django
{{ values|dictsort:"0" }}
@@ -1605,7 +1793,9 @@ but the returned value will be in reverse order.
Returns ``True`` if the value is divisible by the argument.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|divisibleby:"3" }}
@@ -1629,7 +1819,9 @@ 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
multiple escaping passes to be applied, use the :tfilter:`force_escape` filter.
-For example, you can apply ``escape`` to fields when :ttag:`autoescape` is off::
+For example, you can apply ``escape`` to fields when :ttag:`autoescape` is off:
+
+.. code-block:: html+django
{% autoescape off %}
{{ title|escape }}
@@ -1644,7 +1836,9 @@ Escapes characters for use in JavaScript strings. This does *not* make the
string safe for use in HTML or JavaScript template literals, but does protect
you from syntax errors when using templates to generate JavaScript/JSON.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|escapejs }}
@@ -1659,7 +1853,9 @@ the output will be ``"testing\\u000D\\u000Ajavascript \\u0027string\\u0022 \\u00
Formats the value like a 'human-readable' file size (i.e. ``'13 KB'``,
``'4.1 MB'``, ``'102 bytes'``, etc.).
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|filesizeformat }}
@@ -1680,7 +1876,9 @@ If ``value`` is 123456789, the output would be ``117.7 MB``.
Returns the first item in a list.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|first }}
@@ -1775,7 +1973,9 @@ want to apply other filters to the escaped results. Normally, you want to use
the :tfilter:`escape` filter.
For example, if you want to catch the ``<p>`` HTML elements created by
-the :tfilter:`linebreaks` filter::
+the :tfilter:`linebreaks` filter:
+
+.. code-block:: html+django
{% autoescape off %}
{{ body|linebreaks|force_escape }}
@@ -1791,7 +1991,9 @@ digit, 2 is the second-right-most digit, etc. Returns the original value for
invalid input (if input or argument is not an integer, or if argument is less
than 1). Otherwise, output is always an integer.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|get_digit:"2" }}
@@ -1809,7 +2011,9 @@ strings containing non-ASCII characters in a URL.
It's safe to use this filter on a string that has already gone through the
:tfilter:`urlencode` filter.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|iriencode }}
@@ -1822,7 +2026,9 @@ If ``value`` is ``"?test=1&me=2"``, the output will be ``"?test=1&amp;me=2"``.
Joins a list with a string, like Python's ``str.join(list)``
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|join:" // " }}
@@ -1839,7 +2045,9 @@ for use with JavaScript.
**Argument:** The optional HTML "id" of the ``<script>`` tag.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|json_script:"hello-data" }}
@@ -1873,7 +2081,9 @@ executable code.
Returns the last item in a list.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|last }}
@@ -1887,7 +2097,9 @@ string ``"d"``.
Returns the length of the value. This works for both strings and lists.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|length }}
@@ -1905,7 +2117,9 @@ The filter returns ``0`` for an undefined variable.
Returns ``True`` if the value's length is the argument, or ``False`` otherwise.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|length_is:"4" }}
@@ -1921,7 +2135,9 @@ Replaces line breaks in plain text with appropriate HTML; a single
newline becomes an HTML line break (``<br>``) and a new line
followed by a blank line becomes a paragraph break (``</p>``).
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|linebreaks }}
@@ -1936,7 +2152,9 @@ slug</p>``.
Converts all newlines in a piece of plain text to HTML line breaks
(``<br>``).
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|linebreaksbr }}
@@ -1950,17 +2168,23 @@ slug``.
Displays text with line numbers.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|linenumbers }}
-If ``value`` is::
+If ``value`` is:
+
+.. code-block:: html+django
one
two
three
-the output will be::
+the output will be:
+
+.. code-block:: html+django
1. one
2. two
@@ -1975,7 +2199,9 @@ Left-aligns the value in a field of a given width.
**Argument:** field size
-For example::
+For example:
+
+.. code-block:: html+django
"{{ value|ljust:"10" }}"
@@ -1988,7 +2214,9 @@ If ``value`` is ``Django``, the output will be ``"Django "``.
Converts a string into all lowercase.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|lower }}
@@ -2003,7 +2231,9 @@ If ``value`` is ``Totally LOVING this Album!``, the output will be
Returns the value turned into a list. For a string, it's a list of characters.
For an integer, the argument is cast to a string before creating a list.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|make_list }}
@@ -2022,7 +2252,9 @@ equivalent.
The input doesn't have to be a valid phone number. This will happily convert
any string.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|phone2numeric }}
@@ -2036,7 +2268,9 @@ If ``value`` is ``800-COLLECT``, the output will be ``800-2655328``.
Returns a plural suffix if the value is not ``1``, ``'1'``, or an object of
length 1. By default, this suffix is ``'s'``.
-Example::
+Example:
+
+.. code-block:: html+django
You have {{ num_messages }} message{{ num_messages|pluralize }}.
@@ -2046,14 +2280,18 @@ If ``num_messages`` is ``2`` the output will be ``You have 2 messages.``
For words that require a suffix other than ``'s'``, you can provide an alternate
suffix as a parameter to the filter.
-Example::
+Example:
+
+.. code-block:: html+django
You have {{ num_walruses }} walrus{{ num_walruses|pluralize:"es" }}.
For words that don't pluralize by simple suffix, you can specify both a
singular and plural suffix, separated by a comma.
-Example::
+Example:
+
+.. code-block:: html+django
You have {{ num_cherries }} cherr{{ num_cherries|pluralize:"y,ies" }}.
@@ -2073,7 +2311,9 @@ A wrapper around :func:`pprint.pprint` -- for debugging, really.
Returns a random item from the given list.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|random }}
@@ -2088,7 +2328,9 @@ Right-aligns the value in a field of a given width.
**Argument:** field size
-For example::
+For example:
+
+.. code-block:: html+django
"{{ value|rjust:"10" }}"
@@ -2106,7 +2348,9 @@ autoescaping is off, this filter has no effect.
If you are chaining filters, a filter applied after ``safe`` can
make the contents unsafe again. For example, the following code
- prints the variable as is, unescaped::
+ prints the variable as is, unescaped:
+
+ .. code-block:: html+django
{{ var|safe|escape }}
@@ -2117,7 +2361,9 @@ autoescaping is off, this filter has no effect.
Applies the :tfilter:`safe` filter to each element of a sequence. Useful in
conjunction with other filters that operate on sequences, such as
-:tfilter:`join`. For example::
+:tfilter:`join`. For example:
+
+.. code-block:: html+django
{{ some_list|safeseq|join:", " }}
@@ -2136,7 +2382,9 @@ Uses the same syntax as Python's list slicing. See
https://diveinto.org/python3/native-datatypes.html#slicinglists for an
introduction.
-Example::
+Example:
+
+.. code-block:: html+django
{{ some_list|slice:":2" }}
@@ -2151,7 +2399,9 @@ Converts to ASCII. Converts spaces to hyphens. Removes characters that aren't
alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips
leading and trailing whitespace.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|slugify }}
@@ -2166,7 +2416,9 @@ Formats the variable according to the argument, a string formatting specifier.
This specifier uses the :ref:`old-string-formatting` syntax, with the exception
that the leading "%" is dropped.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|stringformat:"E" }}
@@ -2179,7 +2431,9 @@ If ``value`` is ``10``, the output will be ``1.000000E+01``.
Makes all possible efforts to strip all [X]HTML tags.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|striptags }}
@@ -2207,7 +2461,9 @@ Given format can be the predefined one :setting:`TIME_FORMAT`, or a custom
format, same as the :tfilter:`date` filter. Note that the predefined format
is locale-dependent.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|time:"H:i" }}
@@ -2217,7 +2473,9 @@ the string ``"01:23"``.
Note that you can backslash-escape a format string if you want to use the
"raw" value. In this example, both "h" and "m" are backslash-escaped, because
otherwise each is a format string that displays the hour and the month,
-respectively::
+respectively:
+
+.. code-block:: html+django
{{ value|time:"H\h i\m" }}
@@ -2225,7 +2483,9 @@ This would display as "01h 23m".
Another example:
-Assuming that :setting:`LANGUAGE_CODE` is, for example, ``"de"``, then for::
+Assuming that :setting:`LANGUAGE_CODE` is, for example, ``"de"``, then for:
+
+.. code-block:: html+django
{{ value|time:"TIME_FORMAT" }}
@@ -2244,11 +2504,15 @@ accept the timezone-related :ref:`format specifiers
<date-and-time-formatting-specifiers>` ``'e'``, ``'O'`` , ``'T'`` and ``'Z'``.
When used without a format string, the ``TIME_FORMAT`` format specifier is
-used::
+used:
+
+.. code-block:: html+django
{{ value|time }}
-is the same as::
+is the same as:
+
+.. code-block:: html+django
{{ value|time:"TIME_FORMAT" }}
@@ -2263,7 +2527,9 @@ Takes an optional argument that is a variable containing the date to use as
the comparison point (without the argument, the comparison point is *now*).
For example, if ``blog_date`` is a date instance representing midnight on 1
June 2006, and ``comment_date`` is a date instance for 08:00 on 1 June 2006,
-then the following would return "8 hours"::
+then the following would return "8 hours":
+
+.. code-block:: html+django
{{ blog_date|timesince:comment_date }}
@@ -2284,7 +2550,9 @@ given date or datetime. For example, if today is 1 June 2006 and
Takes an optional argument that is a variable containing the date to use as
the comparison point (instead of *now*). If ``from_date`` contains 22 June
-2006, then the following will return "1 week"::
+2006, then the following will return "1 week":
+
+.. code-block:: html+django
{{ conference_date|timeuntil:from_date }}
@@ -2302,7 +2570,9 @@ Converts a string into titlecase by making words start with an uppercase
character and the remaining characters lowercase. This tag makes no effort to
keep "trivial words" in lowercase.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|title }}
@@ -2318,7 +2588,9 @@ Truncated strings will end with a translatable ellipsis character ("…").
**Argument:** Number of characters to truncate to
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|truncatechars:7 }}
@@ -2333,7 +2605,9 @@ Similar to :tfilter:`truncatechars`, except that it is aware of HTML tags. Any
tags that are opened in the string and not closed before the truncation point
are closed immediately after the truncation.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|truncatechars_html:7 }}
@@ -2351,7 +2625,9 @@ Truncates a string after a certain number of words.
**Argument:** Number of words to truncate after
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|truncatewords:2 }}
@@ -2371,7 +2647,9 @@ are closed immediately after the truncation.
This is less efficient than :tfilter:`truncatewords`, so should only be used
when it is being passed HTML text.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|truncatewords_html:2 }}
@@ -2390,7 +2668,9 @@ WITHOUT opening and closing ``<ul>`` tags.
The list is assumed to be in the proper format. For example, if ``var``
contains ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then
-``{{ var|unordered_list }}`` would return::
+``{{ var|unordered_list }}`` would return:
+
+.. code-block:: html+django
<li>States
<ul>
@@ -2411,7 +2691,9 @@ contains ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then
Converts a string into all uppercase.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|upper }}
@@ -2424,7 +2706,9 @@ If ``value`` is ``"Joel is a slug"``, the output will be ``"JOEL IS A SLUG"``.
Escapes a value for use in a URL.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|urlencode }}
@@ -2435,7 +2719,9 @@ An optional argument containing the characters which should not be escaped can
be provided.
If not provided, the '/' character is assumed safe. An empty string can be
-provided when *all* characters should be escaped. For example::
+provided when *all* characters should be escaped. For example:
+
+.. code-block:: html+django
{{ value|urlencode:"" }}
@@ -2463,7 +2749,9 @@ punctuation (opening parens), and ``urlize`` will still do the right thing.
Links generated by ``urlize`` have a ``rel="nofollow"`` attribute added
to them.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|urlize }}
@@ -2498,7 +2786,9 @@ truncates URLs longer than the given character limit.
**Argument:** Number of characters that link text should be truncated to,
including the ellipsis that's added if truncation is necessary.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|urlizetrunc:15 }}
@@ -2515,7 +2805,9 @@ As with urlize_, this filter should only be applied to plain text.
Returns the number of words.
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|wordcount }}
@@ -2530,11 +2822,15 @@ Wraps words at specified line length.
**Argument:** number of characters at which to wrap the text
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|wordwrap:5 }}
-If ``value`` is ``Joel is a slug``, the output would be::
+If ``value`` is ``Joel is a slug``, the output would be:
+
+.. code-block:: html+django
Joel
is a
@@ -2549,7 +2845,9 @@ Maps values for ``True``, ``False``, and (optionally) ``None``, to the strings
"yes", "no", "maybe", or a custom mapping passed as a comma-separated list, and
returns one of those strings according to the value:
-For example::
+For example:
+
+.. code-block:: html+django
{{ value|yesno:"yeah,no,maybe" }}
@@ -2622,19 +2920,25 @@ A set of Django template filters useful for adding a "human touch" to data. See
To link to static files that are saved in :setting:`STATIC_ROOT` Django ships
with a :ttag:`static` template tag. If the :mod:`django.contrib.staticfiles`
app is installed, the tag will serve files using ``url()`` method of the
-storage specified by ``staticfiles`` in :setting:`STORAGES`. For example::
+storage specified by ``staticfiles`` in :setting:`STORAGES`. For example:
+
+.. code-block:: html+django
{% load static %}
<img src="{% static 'images/hi.jpg' %}" alt="Hi!">
It is also able to consume standard context variables, e.g. assuming a
-``user_stylesheet`` variable is passed to the template::
+``user_stylesheet`` variable is passed to the template:
+
+.. code-block:: html+django
{% load static %}
<link rel="stylesheet" href="{% static user_stylesheet %}" media="screen">
If you'd like to retrieve a static URL without displaying it, you can use a
-slightly different call::
+slightly different call:
+
+.. code-block:: html+django
{% load static %}
{% static "images/hi.jpg" as myphoto %}
@@ -2652,13 +2956,17 @@ slightly different call::
You should prefer the :ttag:`static` template tag, but if you need more control
over exactly where and how :setting:`STATIC_URL` is injected into the template,
-you can use the :ttag:`get_static_prefix` template tag::
+you can use the :ttag:`get_static_prefix` template tag:
+
+.. code-block:: html+django
{% load static %}
<img src="{% get_static_prefix %}images/hi.jpg" alt="Hi!">
There's also a second form you can use to avoid extra processing if you need
-the value multiple times::
+the value multiple times:
+
+.. code-block:: html+django
{% load static %}
{% get_static_prefix as STATIC_PREFIX %}
@@ -2672,7 +2980,9 @@ the value multiple times::
~~~~~~~~~~~~~~~~~~~~
Similar to the :ttag:`get_static_prefix`, ``get_media_prefix`` populates a
-template variable with the media prefix :setting:`MEDIA_URL`, e.g.::
+template variable with the media prefix :setting:`MEDIA_URL`, e.g.:
+
+.. code-block:: html+django
{% load static %}
<body data-media-url="{% get_media_prefix %}">
diff --git a/docs/ref/templates/language.txt b/docs/ref/templates/language.txt
index 5a4cce379b..16a3682086 100644
--- a/docs/ref/templates/language.txt
+++ b/docs/ref/templates/language.txt
@@ -34,8 +34,6 @@ or Jinja2_, you should feel right at home with Django's templates.
Templates
=========
-.. highlight:: html+django
-
A template is a text file. It can generate any text-based format (HTML, XML,
CSV, etc.).
@@ -100,7 +98,9 @@ Use a dot (``.``) to access attributes of a variable.
This lookup order can cause some unexpected behavior with objects that
override dictionary lookup. For example, consider the following code snippet
- that attempts to loop over a ``collections.defaultdict``::
+ that attempts to loop over a ``collections.defaultdict``:
+
+ .. code-block:: html+django
{% for k, v in defaultdict.items %}
Do something with k and v here...
@@ -151,7 +151,9 @@ used template filters:
:tfilter:`default`
If a variable is false or empty, use given default. Otherwise, use the
- value of the variable. For example::
+ value of the variable. For example:
+
+ .. code-block:: html+django
{{ value|default:"nothing" }}
@@ -160,7 +162,9 @@ used template filters:
:tfilter:`length`
Returns the length of the value. This works for both strings and lists.
- For example::
+ For example:
+
+ .. code-block:: html+django
{{ value|length }}
@@ -168,7 +172,9 @@ used template filters:
:tfilter:`filesizeformat`
Formats the value like a "human-readable" file size (i.e. ``'13 KB'``,
- ``'4.1 MB'``, ``'102 bytes'``, etc.). For example::
+ ``'4.1 MB'``, ``'102 bytes'``, etc.). For example:
+
+ .. code-block:: html+django
{{ value|filesizeformat }}
@@ -203,7 +209,9 @@ tags:
:ttag:`for`
Loop over each item in an array. For example, to display a list of athletes
- provided in ``athlete_list``::
+ provided in ``athlete_list``:
+
+ .. code-block:: html+django
<ul>
{% for athlete in athlete_list %}
@@ -213,7 +221,9 @@ tags:
:ttag:`if`, ``elif``, and ``else``
Evaluates a variable, and if that variable is "true" the contents of the
- block are displayed::
+ block are displayed:
+
+ .. code-block:: html+django
{% if athlete_list %}
Number of athletes: {{ athlete_list|length }}
@@ -229,7 +239,9 @@ tags:
should be out..." will be displayed. If both lists are empty,
"No athletes." will be displayed.
- You can also use filters and various operators in the :ttag:`if` tag::
+ You can also use filters and various operators in the :ttag:`if` tag:
+
+ .. code-block:: html+django
{% if athlete_list|length > 1 %}
Team: {% for athlete in athlete_list %} ... {% endfor %}
@@ -264,11 +276,15 @@ Comments
To comment-out part of a line in a template, use the comment syntax: ``{# #}``.
-For example, this template would render as ``'hello'``::
+For example, this template would render as ``'hello'``:
+
+.. code-block:: html+django
{# greeting #}hello
-A comment can contain any template code, invalid or not. For example::
+A comment can contain any template code, invalid or not. For example:
+
+.. code-block:: html+django
{# {% if foo %}bar{% else %} #}
@@ -286,7 +302,9 @@ engine is template inheritance. Template inheritance allows you to build a base
"skeleton" template that contains all the common elements of your site and
defines **blocks** that child templates can override.
-Let's look at template inheritance by starting with an example::
+Let's look at template inheritance by starting with an example:
+
+.. code-block:: html+django
<!DOCTYPE html>
<html lang="en">
@@ -319,7 +337,9 @@ In this example, the :ttag:`block` tag defines three blocks that child
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.
-A child template might look like this::
+A child template might look like this:
+
+.. code-block:: html+django
{% extends "base.html" %}
@@ -339,7 +359,9 @@ this template, first it locates the parent -- in this case, "base.html".
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
template. Depending on the value of ``blog_entries``, the output might look
-like::
+like:
+
+.. code-block:: html+django
<!DOCTYPE html>
<html lang="en">
@@ -416,13 +438,17 @@ Here are some tips for working with inheritance:
* Variables created outside of a :ttag:`{% block %}<block>` using the template
tag ``as`` syntax can't be used inside the block. For example, this template
- doesn't render anything::
+ doesn't render anything:
+
+ .. code-block:: html+django
{% translate "Title" as title %}
{% block content %}{{ title }}{% endblock %}
* For extra readability, you can optionally give a *name* to your
- ``{% endblock %}`` tag. For example::
+ ``{% endblock %}`` tag. For example:
+
+ .. code-block:: html+django
{% block content %}
...
@@ -434,7 +460,9 @@ Here are some tips for working with inheritance:
* :ttag:`{% block %}<block>` tags are evaluated first. That's why the content
of a block is always overridden, regardless of the truthiness of surrounding
tags. For example, this template will *always* override the content of the
- ``title`` block::
+ ``title`` block:
+
+ .. code-block:: html+django
{% if change_title %}
{% block title %}Hello!{% endblock title %}
@@ -455,16 +483,22 @@ Automatic HTML escaping
When generating HTML from templates, there's always a risk that a variable will
include characters that affect the resulting HTML. For example, consider this
-template fragment::
+template fragment:
+
+.. code-block:: html+django
Hello, {{ name }}
At first, this seems like a harmless way to display a user's name, but consider
-what would happen if the user entered their name as this::
+what would happen if the user entered their name as this:
+
+.. code-block:: html+django
<script>alert('hello')</script>
-With this name value, the template would be rendered as::
+With this name value, the template would be rendered as:
+
+.. code-block:: html+django
Hello, <script>alert('hello')</script>
@@ -476,7 +510,9 @@ Similarly, what if the name contained a ``'<'`` symbol, like this?
<b>username
-That would result in a rendered template like this::
+That would result in a rendered template like this:
+
+.. code-block:: html+django
Hello, <b>username
@@ -531,14 +567,18 @@ For individual variables
~~~~~~~~~~~~~~~~~~~~~~~~
To disable auto-escaping for an individual variable, use the :tfilter:`safe`
-filter::
+filter:
+
+.. code-block:: html+django
This will be escaped: {{ data }}
This will not be escaped: {{ data|safe }}
Think of *safe* as shorthand for *safe from further escaping* or *can be
safely interpreted as HTML*. In this example, if ``data`` contains ``'<b>'``,
-the output will be::
+the output will be:
+
+.. code-block:: html+django
This will be escaped: &lt;b&gt;
This will not be escaped: <b>
@@ -547,7 +587,9 @@ For template blocks
~~~~~~~~~~~~~~~~~~~
To control auto-escaping for a template, wrap the template (or a particular
-section of the template) in the :ttag:`autoescape` tag, like so::
+section of the template) in the :ttag:`autoescape` tag, like so:
+
+.. code-block:: html+django
{% autoescape off %}
Hello {{ name }}
@@ -555,7 +597,9 @@ section of the template) in the :ttag:`autoescape` tag, like so::
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
-disabled. Here is an example template::
+disabled. Here is an example template:
+
+.. code-block:: html+django
Auto-escaping is on by default. Hello {{ name }}
@@ -590,7 +634,9 @@ just like all block tags. For example:
Because auto-escaping is turned off in the base template, it will also be
turned off in the child template, resulting in the following rendered
-HTML when the ``greeting`` variable contains the string ``<b>Hello!</b>``::
+HTML when the ``greeting`` variable contains the string ``<b>Hello!</b>``:
+
+.. code-block:: html+django
<h1>This &amp; that</h1>
<b>Hello!</b>
@@ -614,7 +660,9 @@ danger of the :tfilter:`escape` filter *double-escaping* data -- the
String literals and automatic escaping
--------------------------------------
-As we mentioned earlier, filter arguments can be strings::
+As we mentioned earlier, filter arguments can be strings:
+
+.. code-block:: html+django
{{ data|default:"This is a string literal." }}
@@ -624,11 +672,15 @@ filter. The reasoning behind this is that the template author is in control of
what goes into the string literal, so they can make sure the text is correctly
escaped when the template is written.
-This means you would write ::
+This means you would write :
+
+.. code-block:: html+django
{{ data|default:"3 &lt; 2" }}
-...rather than::
+...rather than:
+
+.. code-block:: html+django
{{ data|default:"3 < 2" }} {# Bad! Don't do this. #}
@@ -647,7 +699,9 @@ This means that templates have access to much more than just class attributes
ORM provides the :ref:`"entry_set"<topics-db-queries-related>` syntax for
finding a collection of objects related on a foreign key. Therefore, given
a model called "comment" with a foreign key relationship to a model called
-"task" you can loop through all comments attached to a given task like this::
+"task" you can loop through all comments attached to a given task like this:
+
+.. code-block:: html+django
{% for comment in task.comment_set.all %}
{{ comment }}
@@ -655,7 +709,9 @@ a model called "comment" with a foreign key relationship to a model called
Similarly, :doc:`QuerySets</ref/models/querysets>` provide a ``count()`` method
to count the number of objects they contain. Therefore, you can obtain a count
-of all comments related to the current task with::
+of all comments related to the current task with:
+
+.. code-block:: html+django
{{ task.comment_set.all.count }}
@@ -686,7 +742,9 @@ Custom tag and filter libraries
Certain applications provide custom tag and filter libraries. To access them in
a template, ensure the application is in :setting:`INSTALLED_APPS` (we'd add
``'django.contrib.humanize'`` for this example), and then use the :ttag:`load`
-tag in a template::
+tag in a template:
+
+.. code-block:: html+django
{% load humanize %}
@@ -698,7 +756,9 @@ makes the ``intcomma`` filter available for use. If you've enabled
admin to find the list of custom libraries in your installation.
The :ttag:`load` tag can take multiple library names, separated by spaces.
-Example::
+Example:
+
+.. code-block:: html+django
{% load humanize i18n %}