============================ The Django template language ============================ .. admonition:: About this document This document explains the language syntax of the Django template system. If you're looking for a more technical perspective on how it works and how to extend it, see :doc:`/ref/templates/api`. Django's template language is designed to strike a balance between power and ease. It's designed to feel comfortable to those used to working with HTML. If you have any exposure to other text-based template languages, such as Smarty_ or CheetahTemplate_, you should feel right at home with Django's templates. .. admonition:: Philosophy If you have a background in programming, or if you're used to languages like PHP which mix programming code directly into HTML, you'll want to bear in mind that the Django template system is not simply Python embedded into HTML. This is by design: the template system is meant to express presentation, not program logic. The Django template system provides tags which function similarly to some programming constructs -- an :ttag:`if` tag for boolean tests, a :ttag:`for` tag for looping, etc. -- but these are not simply executed as the corresponding Python code, and the template system will not execute arbitrary Python expressions. Only the tags, filters and syntax listed below are supported by default (although you can add :doc:`your own extensions ` to the template language as needed). .. _`The Django template language: For Python programmers`: ../templates_python/ .. _Smarty: http://smarty.php.net/ .. _CheetahTemplate: http://www.cheetahtemplate.org/ Templates ========= .. highlightlang:: html+django A template is simply a text file. It can generate any text-based format (HTML, XML, CSV, etc.). A template contains **variables**, which get replaced with values when the template is evaluated, and **tags**, which control the logic of the template. Below is a minimal template that illustrates a few basics. Each element will be explained later in this document.:: {% extends "base_generic.html" %} {% block title %}{{ section.title }}{% endblock %} {% block content %}
{{ story.tease|truncatewords:"100" }}
{% endfor %} {% endblock %} .. admonition:: Philosophy Why use a text-based template instead of an XML-based one (like Zope's TAL)? We wanted Django's template language to be usable for more than just XML/HTML templates. At World Online, we use it for e-mails, JavaScript and CSV. You can use the template language for any text-based format. Oh, and one more thing: Making humans edit XML is sadistic! Variables ========= Variables look like this: ``{{ variable }}``. When the template engine encounters a variable, it evaluates that variable and replaces it with the result. Use a dot (``.``) to access attributes of a variable. .. admonition:: Behind the scenes Technically, when the template system encounters a dot, it tries the following lookups, in this order: * Dictionary lookup * Attribute lookup * Method call * List-index lookup In the above example, ``{{ section.title }}`` will be replaced with the ``title`` attribute of the ``section`` object. If you use a variable that doesn't exist, the template system will insert the value of the ``TEMPLATE_STRING_IF_INVALID`` setting, which is set to ``''`` (the empty string) by default. See `Using the built-in reference`_, below, for help on finding what variables are available in a given template. Filters ======= You can modify variables for display by using **filters**. Filters look like this: ``{{ name|lower }}``. This displays the value of the ``{{ name }}`` variable after being filtered through the ``lower`` 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. ``{{ text|escape|linebreaks }}`` is a common idiom for escaping text contents, then converting line breaks to ```` tags.
Some filters take arguments. A filter argument looks like this: ``{{
bio|truncatewords:30 }}``. This will display the first 30 words of the ``bio``
variable.
Filter arguments that contain spaces must be quoted; for example, to join a list
with commas and spaced you'd use ``{{ list|join:", " }}``.
Django provides about thirty built-in template filters. You can read all about
them in the :ref:`built-in filter reference {{ entry.body }} This is my first entry. This is my second entry.
{% for athlete in athlete_list %}
:ttag:`if` and ``else``
Evaluates a variable, and if that variable is "true" the contents of the
block are displayed::
{% if athlete_list %}
Number of athletes: {{ athlete_list|length }}
{% else %}
No athletes.
{% endif %}
In the above, if ``athlete_list`` is not empty, the number of athletes
will be displayed by the ``{{ athlete_list|length }}`` variable.
You can also use filters and various operators in the ``if`` tag::
{% if athlete_list|length > 1 %}
Team: {% for athlete in athlete_list %} ... {% endfor %}
{% else %}
Athlete: {{ athlete_list.0.name }}
{% endif %}
:ttag:`block` and :ttag:`extends`
Set up `template inheritance`_ (see below), a powerful way
of cutting down on "boilerplate" in templates.
Again, the above is only a selection of the whole list; see the :ref:`built-in
tag reference {{ entry.title }}
Entry one
Entry two
{% block title %}{% endblock %}
{% block content %}
{% endblock %}
{% endautoescape %}
# child.html
{% extends "base.html" %}
{% block title %}This & that{% endblock %}
{% block content %}{{ greeting }}{% endblock %}
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 ``Hello!``::
This & that
Hello!
Notes
-----
Generally, template authors don't need to worry about auto-escaping very much.
Developers on the Python side (people writing views and custom filters) need to
think about the cases in which data shouldn't be escaped, and mark data
appropriately, so things Just Work in the template.
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
variable that needs escaping. When auto-escaping is on, there's no danger of
the ``escape`` filter *double-escaping* data -- the ``escape`` filter does not
affect auto-escaped variables.
String literals and automatic escaping
--------------------------------------
As we mentioned earlier, filter arguments can be strings::
{{ data|default:"This is a string literal." }}
All string literals are inserted **without** any automatic escaping into the
template -- they act as if they were all passed through the ``safe`` 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 ::
{{ data|default:"3 < 2" }}
...rather than ::
{{ data|default:"3 < 2" }} <-- Bad! Don't do this.
This doesn't affect what happens to data coming from the variable itself.
The variable's contents are still automatically escaped, if necessary, because
they're beyond the control of the template author.
.. _template-built-in-reference:
Using the built-in reference
============================
Django's admin interface includes a complete reference of all template tags and
filters available for a given site. To activate it, follow these steps:
* Add :mod:`django.contrib.admindocs` to your :setting:`INSTALLED_APPS`.
* Add ``(r'^admin/doc/', include('django.contrib.admindocs.urls'))`` to your
:data:`urlpatterns`. Make sure it's included *before* the ``r'^admin/'``
entry, so that requests to ``/admin/doc/`` don't get handled by the
latter entry.
* Install the docutils module (http://docutils.sf.net/).
After you've followed those steps, you can start browsing the documentation by
going to your admin interface and clicking the "Documentation" link in the
upper right of the page.
The reference is divided into 4 sections: tags, filters, models, and views.
The **tags** and **filters** sections describe all the built-in tags (in fact,
the tag and filter references below come directly from those pages) as well as
any custom tag or filter libraries available.
The **views** page is the most valuable. Each URL in your site has a separate
entry here, and clicking on a URL will show you:
* The name of the view function that generates that view.
* A short description of what the view does.
* The **context**, or a list of variables available in the view's template.
* The name of the template or templates that are used for that view.
Each view documentation page also has a bookmarklet that you can use to jump
from any page to the documentation page for that view.
Because Django-powered sites usually use database objects, the **models**
section of the documentation page describes each type of object in the system
along with all the fields available on that object.
Taken together, the documentation pages should tell you every tag, filter,
variable and object available to you in a given template.
.. _loading-custom-template-libraries:
Custom tag and filter libraries
===============================
Certain applications provide custom tag and filter libraries. To access them in
a template, use the ``{% load %}`` tag::
{% load comments %}
{% comment_form for blogs.entries entry.id with is_public yes %}
In the above, the ``load`` tag loads the ``comments`` tag library, which then
makes the ``comment_form`` tag available for use. Consult the documentation
area in your admin to find the list of custom libraries in your installation.
The ``{% load %}`` tag can take multiple library names, separated by spaces.
Example::
{% load comments i18n %}
See :doc:`/howto/custom-template-tags` for information on writing your own custom
template libraries.
Custom libraries and template inheritance
-----------------------------------------
When you load a custom tag or filter library, the tags/filters are only made
available to the current template -- not any parent or child templates along
the template-inheritance path.
For example, if a template ``foo.html`` has ``{% load comments %}``, a child
template (e.g., one that has ``{% extends "foo.html" %}``) will *not* have
access to the comments template tags and filters. The child template is
responsible for its own ``{% load comments %}``.
This is a feature for the sake of maintainability and sanity.