2008-08-23 22:25:40 +00:00
|
|
|
|
====================================================
|
|
|
|
|
The Django template language: For Python programmers
|
|
|
|
|
====================================================
|
|
|
|
|
|
2013-07-15 15:31:06 +00:00
|
|
|
|
.. module:: django.template
|
|
|
|
|
:synopsis: Django's template system
|
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
This document explains the Django template system from a technical
|
|
|
|
|
perspective -- how it works and how to extend it. If you're just looking for
|
2010-08-19 19:27:44 +00:00
|
|
|
|
reference on the language syntax, see :doc:`/topics/templates`.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
|
|
If you're looking to use the Django template system as part of another
|
|
|
|
|
application -- i.e., without the rest of the framework -- make sure to read
|
|
|
|
|
the `configuration`_ section later in this document.
|
|
|
|
|
|
|
|
|
|
.. _configuration: `configuring the template system in standalone mode`_
|
|
|
|
|
|
|
|
|
|
Basics
|
|
|
|
|
======
|
|
|
|
|
|
|
|
|
|
A **template** is a text document, or a normal Python string, that is marked-up
|
|
|
|
|
using the Django template language. A template can contain **block tags** or
|
|
|
|
|
**variables**.
|
|
|
|
|
|
|
|
|
|
A **block tag** is a symbol within a template that does something.
|
|
|
|
|
|
|
|
|
|
This definition is deliberately vague. For example, a block tag can output
|
|
|
|
|
content, serve as a control structure (an "if" statement or "for" loop), grab
|
|
|
|
|
content from a database or enable access to other template tags.
|
|
|
|
|
|
|
|
|
|
Block tags are surrounded by ``"{%"`` and ``"%}"``.
|
|
|
|
|
|
2008-09-09 01:54:20 +00:00
|
|
|
|
Example template with block tags:
|
|
|
|
|
|
|
|
|
|
.. code-block:: html+django
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
|
|
{% if is_logged_in %}Thanks for logging in!{% else %}Please log in.{% endif %}
|
|
|
|
|
|
|
|
|
|
A **variable** is a symbol within a template that outputs a value.
|
|
|
|
|
|
|
|
|
|
Variable tags are surrounded by ``"{{"`` and ``"}}"``.
|
|
|
|
|
|
2008-09-09 01:54:20 +00:00
|
|
|
|
Example template with variables:
|
|
|
|
|
|
|
|
|
|
.. code-block:: html+django
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
|
|
My first name is {{ first_name }}. My last name is {{ last_name }}.
|
|
|
|
|
|
|
|
|
|
A **context** is a "variable name" -> "variable value" mapping that is passed
|
|
|
|
|
to a template.
|
|
|
|
|
|
|
|
|
|
A template **renders** a context by replacing the variable "holes" with values
|
|
|
|
|
from the context and executing all block tags.
|
|
|
|
|
|
|
|
|
|
Using the template system
|
|
|
|
|
=========================
|
|
|
|
|
|
2013-07-15 15:31:06 +00:00
|
|
|
|
.. class:: Template
|
2010-11-29 00:55:04 +00:00
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
Using the template system in Python is a two-step process:
|
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
|
* First, you compile the raw template code into a ``Template`` object.
|
|
|
|
|
* Then, you call the ``render()`` method of the ``Template`` object with a
|
|
|
|
|
given context.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
|
|
Compiling a string
|
|
|
|
|
------------------
|
|
|
|
|
|
|
|
|
|
The easiest way to create a ``Template`` object is by instantiating it
|
2010-11-29 00:55:04 +00:00
|
|
|
|
directly. The class lives at :class:`django.template.Template`. The constructor
|
2008-08-23 22:25:40 +00:00
|
|
|
|
takes one argument -- the raw template code::
|
|
|
|
|
|
|
|
|
|
>>> from django.template import Template
|
|
|
|
|
>>> t = Template("My name is {{ my_name }}.")
|
2012-04-28 16:02:01 +00:00
|
|
|
|
>>> print(t)
|
2008-08-23 22:25:40 +00:00
|
|
|
|
<django.template.Template instance>
|
|
|
|
|
|
|
|
|
|
.. admonition:: Behind the scenes
|
|
|
|
|
|
|
|
|
|
The system only parses your raw template code once -- when you create the
|
|
|
|
|
``Template`` object. From then on, it's stored internally as a "node"
|
|
|
|
|
structure for performance.
|
|
|
|
|
|
|
|
|
|
Even the parsing itself is quite fast. Most of the parsing happens via a
|
|
|
|
|
single call to a single, short, regular expression.
|
|
|
|
|
|
|
|
|
|
Rendering a context
|
|
|
|
|
-------------------
|
|
|
|
|
|
2010-11-29 00:55:04 +00:00
|
|
|
|
.. method:: render(context)
|
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
Once you have a compiled ``Template`` object, you can render a context -- or
|
|
|
|
|
multiple contexts -- with it. The ``Context`` class lives at
|
2010-11-29 00:55:04 +00:00
|
|
|
|
:class:`django.template.Context`, and the constructor takes two (optional)
|
2009-07-16 16:16:13 +00:00
|
|
|
|
arguments:
|
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
|
* A dictionary mapping variable names to variable values.
|
2009-07-16 16:16:13 +00:00
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
|
* The name of the current application. This application name is used
|
|
|
|
|
to help :ref:`resolve namespaced URLs<topics-http-reversing-url-namespaces>`.
|
|
|
|
|
If you're not using namespaced URLs, you can ignore this argument.
|
2009-07-16 16:16:13 +00:00
|
|
|
|
|
|
|
|
|
Call the ``Template`` object's ``render()`` method with the context to "fill" the
|
2008-08-23 22:25:40 +00:00
|
|
|
|
template::
|
|
|
|
|
|
|
|
|
|
>>> from django.template import Context, Template
|
|
|
|
|
>>> t = Template("My name is {{ my_name }}.")
|
|
|
|
|
|
|
|
|
|
>>> c = Context({"my_name": "Adrian"})
|
|
|
|
|
>>> t.render(c)
|
|
|
|
|
"My name is Adrian."
|
|
|
|
|
|
|
|
|
|
>>> c = Context({"my_name": "Dolores"})
|
|
|
|
|
>>> t.render(c)
|
|
|
|
|
"My name is Dolores."
|
|
|
|
|
|
2012-04-10 20:49:45 +00:00
|
|
|
|
Variables and lookups
|
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
Variable names must consist of any letter (A-Z), any digit (0-9), an underscore
|
2012-02-11 12:47:35 +00:00
|
|
|
|
(but they must not start with an underscore) or a dot.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
|
|
Dots have a special meaning in template rendering. A dot in a variable name
|
2011-01-13 13:47:21 +00:00
|
|
|
|
signifies a **lookup**. Specifically, when the template system encounters a
|
|
|
|
|
dot in a variable name, it tries the following lookups, in this order:
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
|
* Dictionary lookup. Example: ``foo["bar"]``
|
|
|
|
|
* Attribute lookup. Example: ``foo.bar``
|
|
|
|
|
* List-index lookup. Example: ``foo[bar]``
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2012-09-01 13:24:39 +00:00
|
|
|
|
Note that "bar" in a template expression like ``{{ foo.bar }}`` will be
|
|
|
|
|
interpreted as a literal string and not using the value of the variable "bar",
|
|
|
|
|
if one exists in the template context.
|
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
The template system uses the first lookup type that works. It's short-circuit
|
2011-01-13 13:47:21 +00:00
|
|
|
|
logic. Here are a few examples::
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
|
|
>>> from django.template import Context, Template
|
|
|
|
|
>>> t = Template("My name is {{ person.first_name }}.")
|
|
|
|
|
>>> d = {"person": {"first_name": "Joe", "last_name": "Johnson"}}
|
|
|
|
|
>>> t.render(Context(d))
|
|
|
|
|
"My name is Joe."
|
|
|
|
|
|
|
|
|
|
>>> class PersonClass: pass
|
|
|
|
|
>>> p = PersonClass()
|
|
|
|
|
>>> p.first_name = "Ron"
|
|
|
|
|
>>> p.last_name = "Nasty"
|
|
|
|
|
>>> t.render(Context({"person": p}))
|
|
|
|
|
"My name is Ron."
|
|
|
|
|
|
|
|
|
|
>>> t = Template("The first stooge in the list is {{ stooges.0 }}.")
|
|
|
|
|
>>> c = Context({"stooges": ["Larry", "Curly", "Moe"]})
|
|
|
|
|
>>> t.render(c)
|
|
|
|
|
"The first stooge in the list is Larry."
|
|
|
|
|
|
2011-01-13 13:47:21 +00:00
|
|
|
|
If any part of the variable is callable, the template system will try calling
|
|
|
|
|
it. Example::
|
|
|
|
|
|
|
|
|
|
>>> class PersonClass2:
|
|
|
|
|
... def name(self):
|
|
|
|
|
... return "Samantha"
|
|
|
|
|
>>> t = Template("My name is {{ person.name }}.")
|
|
|
|
|
>>> t.render(Context({"person": PersonClass2}))
|
|
|
|
|
"My name is Samantha."
|
|
|
|
|
|
|
|
|
|
Callable variables are slightly more complex than variables which only require
|
|
|
|
|
straight lookups. Here are some things to keep in mind:
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
|
* If the variable raises an exception when called, the exception will be
|
|
|
|
|
propagated, unless the exception has an attribute
|
|
|
|
|
``silent_variable_failure`` whose value is ``True``. If the exception
|
|
|
|
|
*does* have a ``silent_variable_failure`` attribute whose value is
|
2014-10-30 22:42:54 +00:00
|
|
|
|
``True``, the variable will render as the value of the
|
2014-12-14 22:13:03 +00:00
|
|
|
|
``string_if_invalid`` configuration option (an empty string, by default).
|
2014-10-30 22:42:54 +00:00
|
|
|
|
Example::
|
2011-10-14 00:12:01 +00:00
|
|
|
|
|
|
|
|
|
>>> t = Template("My name is {{ person.first_name }}.")
|
|
|
|
|
>>> class PersonClass3:
|
|
|
|
|
... def first_name(self):
|
|
|
|
|
... raise AssertionError("foo")
|
|
|
|
|
>>> p = PersonClass3()
|
|
|
|
|
>>> t.render(Context({"person": p}))
|
|
|
|
|
Traceback (most recent call last):
|
|
|
|
|
...
|
|
|
|
|
AssertionError: foo
|
|
|
|
|
|
|
|
|
|
>>> class SilentAssertionError(Exception):
|
|
|
|
|
... silent_variable_failure = True
|
|
|
|
|
>>> class PersonClass4:
|
|
|
|
|
... def first_name(self):
|
|
|
|
|
... raise SilentAssertionError
|
|
|
|
|
>>> p = PersonClass4()
|
|
|
|
|
>>> t.render(Context({"person": p}))
|
|
|
|
|
"My name is ."
|
|
|
|
|
|
|
|
|
|
Note that :exc:`django.core.exceptions.ObjectDoesNotExist`, which is the
|
|
|
|
|
base class for all Django database API ``DoesNotExist`` exceptions, has
|
|
|
|
|
``silent_variable_failure = True``. So if you're using Django templates
|
|
|
|
|
with Django model objects, any ``DoesNotExist`` exception will fail
|
|
|
|
|
silently.
|
|
|
|
|
|
|
|
|
|
* A variable can only be called if it has no required arguments. Otherwise,
|
2014-12-14 22:13:03 +00:00
|
|
|
|
the system will return the value of the ``string_if_invalid`` option.
|
2011-10-14 00:12:01 +00:00
|
|
|
|
|
2012-08-18 13:46:17 +00:00
|
|
|
|
.. _alters-data-description:
|
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
|
* Obviously, there can be side effects when calling some variables, and
|
|
|
|
|
it'd be either foolish or a security hole to allow the template system
|
|
|
|
|
to access them.
|
|
|
|
|
|
|
|
|
|
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::
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
``alters_data=True`` set, and will instead replace the variable with
|
2014-12-14 22:13:03 +00:00
|
|
|
|
``string_if_invalid``, unconditionally. The
|
2011-10-14 00:12:01 +00:00
|
|
|
|
dynamically-generated :meth:`~django.db.models.Model.delete` and
|
|
|
|
|
:meth:`~django.db.models.Model.save` methods on Django model objects get
|
|
|
|
|
``alters_data=True`` automatically. Example::
|
|
|
|
|
|
|
|
|
|
def sensitive_function(self):
|
|
|
|
|
self.database_record.delete()
|
|
|
|
|
sensitive_function.alters_data = True
|
|
|
|
|
|
2012-12-26 20:47:29 +00:00
|
|
|
|
* Occasionally you may want to turn off this feature for other reasons,
|
2014-02-28 16:44:03 +00:00
|
|
|
|
and tell the template system to leave a variable uncalled no matter
|
2012-12-26 20:47:29 +00:00
|
|
|
|
what. To do so, set a ``do_not_call_in_templates`` attribute on the
|
|
|
|
|
callable with the value ``True``. The template system then will act as
|
|
|
|
|
if your variable is not callable (allowing you to access attributes of
|
|
|
|
|
the callable, for example).
|
2011-04-19 22:06:19 +00:00
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
.. _invalid-template-variables:
|
|
|
|
|
|
|
|
|
|
How invalid variables are handled
|
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
|
|
Generally, if a variable doesn't exist, the template system inserts the
|
2014-12-14 22:13:03 +00:00
|
|
|
|
value of the ``string_if_invalid`` configuration option, which is set to
|
2008-08-23 22:25:40 +00:00
|
|
|
|
``''`` (the empty string) by default.
|
|
|
|
|
|
|
|
|
|
Filters that are applied to an invalid variable will only be applied if
|
2014-12-14 22:13:03 +00:00
|
|
|
|
``string_if_invalid`` is set to ``''`` (the empty string). If
|
|
|
|
|
``string_if_invalid`` is set to any other value, variable filters will be
|
|
|
|
|
ignored.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
|
|
This behavior is slightly different for the ``if``, ``for`` and ``regroup``
|
|
|
|
|
template tags. If an invalid variable is provided to one of these template
|
|
|
|
|
tags, the variable will be interpreted as ``None``. Filters are always
|
|
|
|
|
applied to invalid variables within these template tags.
|
|
|
|
|
|
2014-12-14 22:13:03 +00:00
|
|
|
|
If ``string_if_invalid`` contains a ``'%s'``, the format marker will be
|
|
|
|
|
replaced with the name of the invalid variable.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
|
|
.. admonition:: For debug purposes only!
|
|
|
|
|
|
2014-12-14 22:13:03 +00:00
|
|
|
|
While ``string_if_invalid`` can be a useful debugging tool, it is a bad
|
|
|
|
|
idea to turn it on as a 'development default'.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-12-14 22:13:03 +00:00
|
|
|
|
Many templates, including those in the Admin site, rely upon the silence
|
|
|
|
|
of the template system when a non-existent variable is encountered. If you
|
|
|
|
|
assign a value other than ``''`` to ``string_if_invalid``, you will
|
|
|
|
|
experience rendering problems with these templates and sites.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-12-14 22:13:03 +00:00
|
|
|
|
Generally, ``string_if_invalid`` should only be enabled in order to debug
|
|
|
|
|
a specific template problem, then cleared once debugging is complete.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2012-04-10 20:49:45 +00:00
|
|
|
|
Builtin variables
|
|
|
|
|
~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
|
|
Every context contains ``True``, ``False`` and ``None``. As you would expect,
|
|
|
|
|
these variables resolve to the corresponding Python objects.
|
|
|
|
|
|
2014-08-26 14:35:32 +00:00
|
|
|
|
Limitations with string literals
|
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
|
|
Django's template language has no way to escape the characters used for its own
|
|
|
|
|
syntax. For example, the :ttag:`templatetag` tag is required if you need to
|
|
|
|
|
output character sequences like ``{%`` and ``%}``.
|
|
|
|
|
|
|
|
|
|
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::
|
|
|
|
|
|
|
|
|
|
{% 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::
|
|
|
|
|
|
|
|
|
|
{{ some.variable|default:"}}" }}
|
|
|
|
|
|
|
|
|
|
If you need to use strings with these sequences, store them in template
|
|
|
|
|
variables or use a custom template tag or filter to workaround the limitation.
|
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
Playing with Context objects
|
|
|
|
|
----------------------------
|
|
|
|
|
|
2013-07-15 15:31:06 +00:00
|
|
|
|
.. class:: Context
|
2010-11-29 00:55:04 +00:00
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
Most of the time, you'll instantiate ``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::
|
|
|
|
|
|
2013-05-19 09:44:34 +00:00
|
|
|
|
>>> from django.template import Context
|
2008-08-23 22:25:40 +00:00
|
|
|
|
>>> c = Context({"foo": "bar"})
|
|
|
|
|
>>> c['foo']
|
|
|
|
|
'bar'
|
|
|
|
|
>>> del c['foo']
|
|
|
|
|
>>> c['foo']
|
|
|
|
|
''
|
|
|
|
|
>>> c['newvariable'] = 'hello'
|
|
|
|
|
>>> c['newvariable']
|
|
|
|
|
'hello'
|
|
|
|
|
|
2013-07-15 15:31:06 +00:00
|
|
|
|
.. method:: Context.pop()
|
|
|
|
|
.. method:: Context.push()
|
|
|
|
|
.. exception:: ContextPopException
|
2010-11-29 00:55:04 +00:00
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
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``::
|
|
|
|
|
|
|
|
|
|
>>> c = Context()
|
|
|
|
|
>>> c['foo'] = 'first level'
|
|
|
|
|
>>> c.push()
|
2013-11-27 23:53:10 +00:00
|
|
|
|
{}
|
2008-08-23 22:25:40 +00:00
|
|
|
|
>>> c['foo'] = 'second level'
|
|
|
|
|
>>> c['foo']
|
|
|
|
|
'second level'
|
|
|
|
|
>>> c.pop()
|
2013-11-27 23:53:10 +00:00
|
|
|
|
{'foo': 'second level'}
|
2008-08-23 22:25:40 +00:00
|
|
|
|
>>> c['foo']
|
|
|
|
|
'first level'
|
|
|
|
|
>>> c['foo'] = 'overwritten'
|
|
|
|
|
>>> c['foo']
|
|
|
|
|
'overwritten'
|
|
|
|
|
>>> c.pop()
|
|
|
|
|
Traceback (most recent call last):
|
|
|
|
|
...
|
2014-08-19 00:37:16 +00:00
|
|
|
|
ContextPopException
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2013-07-16 11:11:32 +00:00
|
|
|
|
.. versionadded:: 1.7
|
|
|
|
|
|
|
|
|
|
You can also use ``push()`` as a context manager to ensure a matching ``pop()``
|
|
|
|
|
is called.
|
|
|
|
|
|
|
|
|
|
>>> c = Context()
|
|
|
|
|
>>> c['foo'] = 'first level'
|
|
|
|
|
>>> with c.push():
|
|
|
|
|
>>> c['foo'] = 'second level'
|
|
|
|
|
>>> c['foo']
|
|
|
|
|
'second level'
|
|
|
|
|
>>> c['foo']
|
|
|
|
|
'first level'
|
|
|
|
|
|
|
|
|
|
All arguments passed to ``push()`` will be passed to the ``dict`` constructor
|
|
|
|
|
used to build the new context level.
|
|
|
|
|
|
|
|
|
|
>>> c = Context()
|
|
|
|
|
>>> c['foo'] = 'first level'
|
|
|
|
|
>>> with c.push(foo='second level'):
|
|
|
|
|
>>> c['foo']
|
|
|
|
|
'second level'
|
|
|
|
|
>>> c['foo']
|
|
|
|
|
'first level'
|
|
|
|
|
|
2010-11-29 00:55:04 +00:00
|
|
|
|
.. method:: update(other_dict)
|
|
|
|
|
|
2010-11-24 00:36:36 +00:00
|
|
|
|
In addition to ``push()`` and ``pop()``, the ``Context``
|
|
|
|
|
object also defines an ``update()`` method. This works like ``push()``
|
|
|
|
|
but takes a dictionary as an argument and pushes that dictionary onto
|
|
|
|
|
the stack instead of an empty one.
|
|
|
|
|
|
|
|
|
|
>>> c = Context()
|
|
|
|
|
>>> c['foo'] = 'first level'
|
|
|
|
|
>>> c.update({'foo': 'updated'})
|
|
|
|
|
{'foo': 'updated'}
|
|
|
|
|
>>> c['foo']
|
|
|
|
|
'updated'
|
|
|
|
|
>>> c.pop()
|
|
|
|
|
{'foo': 'updated'}
|
|
|
|
|
>>> c['foo']
|
|
|
|
|
'first level'
|
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
Using a ``Context`` as a stack comes in handy in some custom template tags, as
|
|
|
|
|
you'll see below.
|
|
|
|
|
|
2014-02-16 13:50:27 +00:00
|
|
|
|
.. method:: Context.flatten()
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 1.7
|
|
|
|
|
|
|
|
|
|
Using ``flatten()`` method you can get whole ``Context`` stack as one dictionary
|
|
|
|
|
including builtin variables.
|
|
|
|
|
|
|
|
|
|
>>> c = Context()
|
|
|
|
|
>>> c['foo'] = 'first level'
|
|
|
|
|
>>> c.update({'bar': 'second level'})
|
|
|
|
|
{'bar': 'second level'}
|
|
|
|
|
>>> c.flatten()
|
|
|
|
|
{'True': True, 'None': None, 'foo': 'first level', 'False': False, 'bar': 'second level'}
|
|
|
|
|
|
|
|
|
|
A ``flatten()`` method is also internally used to make ``Context`` objects comparable.
|
|
|
|
|
|
|
|
|
|
>>> c1 = Context()
|
|
|
|
|
>>> c1['foo'] = 'first level'
|
|
|
|
|
>>> c1['bar'] = 'second level'
|
|
|
|
|
>>> c2 = Context()
|
|
|
|
|
>>> c2.update({'bar': 'second level', 'foo': 'first level'})
|
|
|
|
|
{'foo': 'first level', 'bar': 'second level'}
|
|
|
|
|
>>> c1 == c2
|
|
|
|
|
True
|
|
|
|
|
|
|
|
|
|
Result from ``flatten()`` can be useful in unit tests to compare ``Context``
|
|
|
|
|
against ``dict``::
|
|
|
|
|
|
|
|
|
|
class ContextTest(unittest.TestCase):
|
|
|
|
|
def test_against_dictionary(self):
|
|
|
|
|
c1 = Context()
|
|
|
|
|
c1['update'] = 'value'
|
|
|
|
|
self.assertEqual(c1.flatten(), {
|
|
|
|
|
'True': True, 'None': None, 'False': False,
|
|
|
|
|
'update': 'value'})
|
|
|
|
|
|
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
.. _subclassing-context-requestcontext:
|
|
|
|
|
|
|
|
|
|
Subclassing Context: RequestContext
|
|
|
|
|
-----------------------------------
|
|
|
|
|
|
2013-07-15 15:31:06 +00:00
|
|
|
|
.. class:: RequestContext
|
2010-10-20 01:33:24 +00:00
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
Django comes with a special ``Context`` class,
|
|
|
|
|
``django.template.RequestContext``, that acts slightly differently than the
|
|
|
|
|
normal ``django.template.Context``. The first difference is that it takes an
|
|
|
|
|
:class:`~django.http.HttpRequest` as its first argument. For example::
|
|
|
|
|
|
|
|
|
|
c = RequestContext(request, {
|
|
|
|
|
'foo': 'bar',
|
2008-09-27 03:25:42 +00:00
|
|
|
|
})
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-12-17 22:36:32 +00:00
|
|
|
|
The second difference is that it automatically populates the context with a
|
|
|
|
|
few variables, according to the ``'context_processors'`` option in the
|
|
|
|
|
:setting:`TEMPLATES` setting.
|
|
|
|
|
|
|
|
|
|
The ``'context_processors'`` option is a list of callables -- called **context
|
|
|
|
|
processors** -- that take a request object as their argument and return a
|
|
|
|
|
dictionary of items to be merged into the context. In the default generated
|
|
|
|
|
settings file, the default template engine contains the following context
|
|
|
|
|
processors::
|
|
|
|
|
|
|
|
|
|
[
|
|
|
|
|
'django.contrib.auth.context_processors.auth',
|
|
|
|
|
'django.template.context_processors.debug',
|
|
|
|
|
'django.template.context_processors.i18n',
|
|
|
|
|
'django.template.context_processors.media',
|
|
|
|
|
'django.template.context_processors.static',
|
|
|
|
|
'django.template.context_processors.tz',
|
|
|
|
|
'django.contrib.messages.context_processors.messages',
|
|
|
|
|
]
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 1.8
|
|
|
|
|
|
|
|
|
|
Built-in template context processors were moved from
|
|
|
|
|
``django.core.context_processors`` to
|
|
|
|
|
``django.template.context_processors`` in Django 1.8.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2012-06-07 13:02:35 +00:00
|
|
|
|
In addition to these, ``RequestContext`` always uses
|
2014-12-02 22:23:51 +00:00
|
|
|
|
``django.template.context_processors.csrf``. This is a security
|
2012-06-07 13:02:35 +00:00
|
|
|
|
related context processor required by the admin and other contrib apps, and,
|
|
|
|
|
in case of accidental misconfiguration, it is deliberately hardcoded in and
|
2014-12-17 22:36:32 +00:00
|
|
|
|
cannot be turned off in the ``'context_processors'`` option.
|
2010-02-26 17:06:09 +00:00
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
Each processor is applied in order. That means, if one processor adds a
|
|
|
|
|
variable to the context and a second processor adds a variable with the same
|
|
|
|
|
name, the second will override the first. The default processors are explained
|
|
|
|
|
below.
|
|
|
|
|
|
2010-03-03 08:43:05 +00:00
|
|
|
|
.. admonition:: When context processors are applied
|
2010-03-10 00:58:05 +00:00
|
|
|
|
|
2014-05-16 15:52:59 +00:00
|
|
|
|
Context processors are applied *after* the context itself is processed.
|
|
|
|
|
This means that a context processor may overwrite variables you've
|
|
|
|
|
supplied to your ``Context`` or ``RequestContext``, so take care
|
|
|
|
|
to avoid variable names that overlap with those supplied by your
|
|
|
|
|
context processors.
|
2010-03-03 08:43:05 +00:00
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
Also, you can give ``RequestContext`` a list of additional processors, using the
|
|
|
|
|
optional, third positional argument, ``processors``. In this example, the
|
|
|
|
|
``RequestContext`` instance gets a ``ip_address`` variable::
|
|
|
|
|
|
2013-05-19 09:44:34 +00:00
|
|
|
|
from django.http import HttpResponse
|
|
|
|
|
from django.template import RequestContext
|
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
def ip_address_processor(request):
|
|
|
|
|
return {'ip_address': request.META['REMOTE_ADDR']}
|
|
|
|
|
|
|
|
|
|
def some_view(request):
|
|
|
|
|
# ...
|
|
|
|
|
c = RequestContext(request, {
|
|
|
|
|
'foo': 'bar',
|
|
|
|
|
}, [ip_address_processor])
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 18:30:54 +00:00
|
|
|
|
return HttpResponse(t.render(c))
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
|
|
.. note::
|
2011-09-16 18:06:42 +00:00
|
|
|
|
|
2011-05-21 18:36:01 +00:00
|
|
|
|
If you're using Django's :func:`~django.shortcuts.render_to_response()`
|
|
|
|
|
shortcut to populate a template with the contents of a dictionary, your
|
|
|
|
|
template will be passed a ``Context`` instance by default (not a
|
2011-09-16 18:06:42 +00:00
|
|
|
|
``RequestContext``). To use a ``RequestContext`` in your template
|
2014-10-30 22:34:10 +00:00
|
|
|
|
rendering, use the :meth:`~django.shortcuts.render()` shortcut which is
|
2012-09-01 00:24:33 +00:00
|
|
|
|
the same as a call to :func:`~django.shortcuts.render_to_response()` with a
|
2014-10-30 22:34:10 +00:00
|
|
|
|
``context_instance`` argument that forces the use of a ``RequestContext``.
|
2014-05-16 15:52:59 +00:00
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
Here's what each of the default processors does:
|
|
|
|
|
|
2010-02-21 23:40:47 +00:00
|
|
|
|
django.contrib.auth.context_processors.auth
|
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-12-17 22:36:32 +00:00
|
|
|
|
If this processor is enabled, every ``RequestContext`` will contain these
|
|
|
|
|
variables:
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
|
* ``user`` -- An ``auth.User`` instance representing the currently
|
|
|
|
|
logged-in user (or an ``AnonymousUser`` instance, if the client isn't
|
|
|
|
|
logged in).
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
|
* ``perms`` -- An instance of
|
|
|
|
|
``django.contrib.auth.context_processors.PermWrapper``, representing the
|
|
|
|
|
permissions that the currently logged-in user has.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-12-02 22:23:51 +00:00
|
|
|
|
.. currentmodule:: django.template.context_processors
|
2013-07-15 15:31:06 +00:00
|
|
|
|
|
2014-12-02 22:23:51 +00:00
|
|
|
|
django.template.context_processors.debug
|
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-12-17 22:36:32 +00:00
|
|
|
|
If this processor is enabled, every ``RequestContext`` will contain these two
|
|
|
|
|
variables -- but only if your :setting:`DEBUG` setting is set to ``True`` and
|
|
|
|
|
the request's IP address (``request.META['REMOTE_ADDR']``) is in the
|
|
|
|
|
:setting:`INTERNAL_IPS` setting:
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
|
* ``debug`` -- ``True``. You can use this in templates to test whether
|
|
|
|
|
you're in :setting:`DEBUG` mode.
|
|
|
|
|
* ``sql_queries`` -- A list of ``{'sql': ..., 'time': ...}`` dictionaries,
|
|
|
|
|
representing every SQL query that has happened so far during the request
|
2014-08-27 08:41:12 +00:00
|
|
|
|
and how long it took. The list is in order by query and lazily generated
|
|
|
|
|
on access.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-12-02 22:23:51 +00:00
|
|
|
|
django.template.context_processors.i18n
|
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-12-17 22:36:32 +00:00
|
|
|
|
If this processor is enabled, every ``RequestContext`` will contain these two
|
|
|
|
|
variables:
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
|
* ``LANGUAGES`` -- The value of the :setting:`LANGUAGES` setting.
|
|
|
|
|
* ``LANGUAGE_CODE`` -- ``request.LANGUAGE_CODE``, if it exists. Otherwise,
|
|
|
|
|
the value of the :setting:`LANGUAGE_CODE` setting.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2010-08-19 19:27:44 +00:00
|
|
|
|
See :doc:`/topics/i18n/index` for more.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-12-02 22:23:51 +00:00
|
|
|
|
django.template.context_processors.media
|
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-12-17 22:36:32 +00:00
|
|
|
|
If this processor is enabled, every ``RequestContext`` will contain a variable
|
|
|
|
|
``MEDIA_URL``, providing the value of the :setting:`MEDIA_URL` setting.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-12-02 22:23:51 +00:00
|
|
|
|
django.template.context_processors.static
|
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2010-11-17 15:36:26 +00:00
|
|
|
|
|
2013-07-15 15:31:06 +00:00
|
|
|
|
.. function:: static
|
2011-06-30 09:06:19 +00:00
|
|
|
|
|
2014-12-17 22:36:32 +00:00
|
|
|
|
If this processor is enabled, every ``RequestContext`` will contain a variable
|
|
|
|
|
``STATIC_URL``, providing the value of the :setting:`STATIC_URL` setting.
|
2010-11-17 15:36:26 +00:00
|
|
|
|
|
2014-12-02 22:23:51 +00:00
|
|
|
|
django.template.context_processors.csrf
|
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-26 23:23:07 +00:00
|
|
|
|
|
2011-10-03 08:06:01 +00:00
|
|
|
|
This processor adds a token that is needed by the :ttag:`csrf_token` template
|
|
|
|
|
tag for protection against :doc:`Cross Site Request Forgeries
|
2014-10-31 22:39:46 +00:00
|
|
|
|
</ref/csrf>`.
|
Fixed #9977 - CsrfMiddleware gets template tag added, session dependency removed, and turned on by default.
This is a large change to CSRF protection for Django. It includes:
* removing the dependency on the session framework.
* deprecating CsrfResponseMiddleware, and replacing with a core template tag.
* turning on CSRF protection by default by adding CsrfViewMiddleware to
the default value of MIDDLEWARE_CLASSES.
* protecting all contrib apps (whatever is in settings.py)
using a decorator.
For existing users of the CSRF functionality, it should be a seamless update,
but please note that it includes DEPRECATION of features in Django 1.1,
and there are upgrade steps which are detailed in the docs.
Many thanks to 'Glenn' and 'bthomas', who did a lot of the thinking and work
on the patch, and to lots of other people including Simon Willison and
Russell Keith-Magee who refined the ideas.
Details of the rationale for these changes is found here:
http://code.djangoproject.com/wiki/CsrfProtection
As of this commit, the CSRF code is mainly in 'contrib'. The code will be
moved to core in a separate commit, to make the changeset as readable as
possible.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@11660 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-10-26 23:23:07 +00:00
|
|
|
|
|
2014-12-02 22:23:51 +00:00
|
|
|
|
django.template.context_processors.request
|
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-12-17 22:36:32 +00:00
|
|
|
|
If this processor is enabled, every ``RequestContext`` will contain a variable
|
|
|
|
|
``request``, which is the current :class:`~django.http.HttpRequest`. Note that
|
|
|
|
|
this processor is not enabled by default; you'll have to activate it.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2009-12-09 16:57:23 +00:00
|
|
|
|
django.contrib.messages.context_processors.messages
|
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
2014-12-17 22:36:32 +00:00
|
|
|
|
If this processor is enabled, every ``RequestContext`` will contain these two
|
|
|
|
|
variables:
|
2009-12-09 16:57:23 +00:00
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
|
* ``messages`` -- A list of messages (as strings) that have been set
|
2014-05-06 18:37:48 +00:00
|
|
|
|
via the :doc:`messages framework </ref/contrib/messages>`.
|
|
|
|
|
* ``DEFAULT_MESSAGE_LEVELS`` -- A mapping of the message level names to
|
|
|
|
|
:ref:`their numeric value <message-level-constants>`.
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 1.7
|
|
|
|
|
|
|
|
|
|
The ``DEFAULT_MESSAGE_LEVELS`` variable was added.
|
2009-12-09 16:57:23 +00:00
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
Writing your own context processors
|
|
|
|
|
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
|
|
A context processor has a very simple interface: It's just a Python function
|
2010-11-29 00:55:04 +00:00
|
|
|
|
that takes one argument, an :class:`~django.http.HttpRequest` object, and
|
|
|
|
|
returns a dictionary that gets added to the template context. Each context
|
|
|
|
|
processor *must* return a dictionary.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-12-17 22:36:32 +00:00
|
|
|
|
Custom context processors can live anywhere in your code base. All Django
|
|
|
|
|
cares about is that your custom context processors are pointed to by the
|
|
|
|
|
``'context_processors'`` option in your :setting:`TEMPLATES` setting.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
|
|
Loading templates
|
|
|
|
|
-----------------
|
|
|
|
|
|
|
|
|
|
Generally, you'll store templates in files on your filesystem rather than using
|
|
|
|
|
the low-level ``Template`` API yourself. Save templates in a directory
|
|
|
|
|
specified as a **template directory**.
|
|
|
|
|
|
|
|
|
|
Django searches for template directories in a number of places, depending on
|
|
|
|
|
your template-loader settings (see "Loader types" below), but the most basic
|
2014-12-17 21:51:42 +00:00
|
|
|
|
way of specifying template directories is by using the :setting:`DIRS
|
|
|
|
|
<TEMPLATES-DIRS>` option.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-12-17 21:51:42 +00:00
|
|
|
|
The DIRS option
|
|
|
|
|
~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
|
|
.. versionchanged:: 1.8
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-12-17 21:51:42 +00:00
|
|
|
|
This value used to be defined by the ``TEMPLATE_DIRS`` setting.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-12-17 21:51:42 +00:00
|
|
|
|
Tell Django what your template directories are by using the :setting:`DIRS
|
|
|
|
|
<TEMPLATES-DIRS>` option in the :setting:`TEMPLATES` setting in your settings
|
|
|
|
|
file. This should be set to a list of strings that contain full paths to your
|
|
|
|
|
template directory(ies). Example::
|
|
|
|
|
|
|
|
|
|
TEMPLATES = [
|
|
|
|
|
{
|
|
|
|
|
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
|
|
|
|
'DIRS': [
|
|
|
|
|
'/home/html/templates/lawrence.com',
|
|
|
|
|
'/home/html/templates/default',
|
|
|
|
|
],
|
|
|
|
|
},
|
|
|
|
|
]
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
|
|
Your templates can go anywhere you want, as long as the directories and
|
|
|
|
|
templates are readable by the Web server. They can have any extension you want,
|
|
|
|
|
such as ``.html`` or ``.txt``, or they can have no extension at all.
|
|
|
|
|
|
|
|
|
|
Note that these paths should use Unix-style forward slashes, even on Windows.
|
|
|
|
|
|
|
|
|
|
.. _ref-templates-api-the-python-api:
|
|
|
|
|
|
|
|
|
|
The Python API
|
|
|
|
|
~~~~~~~~~~~~~~
|
|
|
|
|
|
2013-01-01 13:12:42 +00:00
|
|
|
|
.. module:: django.template.loader
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2013-01-01 13:12:42 +00:00
|
|
|
|
``django.template.loader`` has two functions to load templates from files:
|
|
|
|
|
|
2013-09-15 21:51:24 +00:00
|
|
|
|
.. function:: get_template(template_name[, dirs])
|
2009-12-25 20:51:30 +00:00
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
``get_template`` returns the compiled template (a ``Template`` object) for
|
|
|
|
|
the template with the given name. If the template doesn't exist, it raises
|
|
|
|
|
``django.template.TemplateDoesNotExist``.
|
|
|
|
|
|
2013-09-15 21:51:24 +00:00
|
|
|
|
.. versionchanged:: 1.7
|
|
|
|
|
|
|
|
|
|
The ``dirs`` parameter was added.
|
|
|
|
|
|
2014-11-13 19:25:08 +00:00
|
|
|
|
.. versionchanged:: 1.8
|
|
|
|
|
|
|
|
|
|
The ``dirs`` parameter was deprecated.
|
|
|
|
|
|
2013-09-15 21:51:24 +00:00
|
|
|
|
.. function:: select_template(template_name_list[, dirs])
|
2009-12-25 20:51:30 +00:00
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
``select_template`` is just like ``get_template``, except it takes a list
|
|
|
|
|
of template names. Of the list, it returns the first template that exists.
|
|
|
|
|
|
2013-09-15 21:51:24 +00:00
|
|
|
|
.. versionchanged:: 1.7
|
|
|
|
|
|
|
|
|
|
The ``dirs`` parameter was added.
|
|
|
|
|
|
2014-11-13 19:25:08 +00:00
|
|
|
|
.. versionchanged:: 1.8
|
|
|
|
|
|
|
|
|
|
The ``dirs`` parameter was deprecated.
|
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
For example, if you call ``get_template('story_detail.html')`` and have the
|
2014-12-17 21:51:42 +00:00
|
|
|
|
above :setting:`DIRS <TEMPLATES-DIRS>` option, here are the files Django will
|
|
|
|
|
look for, in order:
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
|
* ``/home/html/templates/lawrence.com/story_detail.html``
|
|
|
|
|
* ``/home/html/templates/default/story_detail.html``
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
|
|
If you call ``select_template(['story_253_detail.html', 'story_detail.html'])``,
|
|
|
|
|
here's what Django will look for:
|
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
|
* ``/home/html/templates/lawrence.com/story_253_detail.html``
|
|
|
|
|
* ``/home/html/templates/default/story_253_detail.html``
|
|
|
|
|
* ``/home/html/templates/lawrence.com/story_detail.html``
|
|
|
|
|
* ``/home/html/templates/default/story_detail.html``
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
|
|
When Django finds a template that exists, it stops looking.
|
|
|
|
|
|
|
|
|
|
.. admonition:: Tip
|
|
|
|
|
|
|
|
|
|
You can use ``select_template()`` for super-flexible "templatability." For
|
|
|
|
|
example, if you've written a news story and want some stories to have
|
|
|
|
|
custom templates, use something like
|
|
|
|
|
``select_template(['story_%s_detail.html' % story.id, 'story_detail.html'])``.
|
|
|
|
|
That'll allow you to use a custom template for an individual story, with a
|
|
|
|
|
fallback template for stories that don't have custom templates.
|
|
|
|
|
|
|
|
|
|
Using subdirectories
|
|
|
|
|
~~~~~~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
|
|
It's possible -- and preferable -- to organize templates in subdirectories of
|
|
|
|
|
the template directory. The convention is to make a subdirectory for each
|
|
|
|
|
Django app, with subdirectories within those subdirectories as needed.
|
|
|
|
|
|
|
|
|
|
Do this for your own sanity. Storing all templates in the root level of a
|
|
|
|
|
single directory gets messy.
|
|
|
|
|
|
|
|
|
|
To load a template that's within a subdirectory, just use a slash, like so::
|
|
|
|
|
|
|
|
|
|
get_template('news/story_detail.html')
|
|
|
|
|
|
2014-12-17 21:51:42 +00:00
|
|
|
|
Using the same :setting:`DIRS <TEMPLATES-DIRS>` option from above, this
|
|
|
|
|
example ``get_template()`` call will attempt to load the following templates:
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
|
* ``/home/html/templates/lawrence.com/news/story_detail.html``
|
|
|
|
|
* ``/home/html/templates/default/news/story_detail.html``
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
|
|
.. _template-loaders:
|
|
|
|
|
|
|
|
|
|
Loader types
|
|
|
|
|
~~~~~~~~~~~~
|
|
|
|
|
|
|
|
|
|
By default, Django uses a filesystem-based template loader, but Django comes
|
|
|
|
|
with a few other template loaders, which know how to load templates from other
|
|
|
|
|
sources.
|
|
|
|
|
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 18:30:54 +00:00
|
|
|
|
Some of these other loaders are disabled by default, but you can activate them
|
2014-12-17 21:10:57 +00:00
|
|
|
|
by adding a ``'loaders'`` option to your ``DjangoTemplates`` backend in the
|
|
|
|
|
:setting:`TEMPLATES` setting. ``'loaders'`` should be a list of strings or
|
|
|
|
|
tuples, where each represents a template loader class. Here are the template
|
|
|
|
|
loaders that come with Django:
|
2011-01-25 15:42:24 +00:00
|
|
|
|
|
2013-01-01 13:12:42 +00:00
|
|
|
|
.. currentmodule:: django.template.loaders
|
|
|
|
|
|
2009-12-14 12:08:23 +00:00
|
|
|
|
``django.template.loaders.filesystem.Loader``
|
2013-01-01 13:12:42 +00:00
|
|
|
|
|
|
|
|
|
.. class:: filesystem.Loader
|
|
|
|
|
|
2014-12-17 21:10:57 +00:00
|
|
|
|
Loads templates from the filesystem, according to
|
|
|
|
|
:setting:`DIRS <TEMPLATES-DIRS>`.
|
|
|
|
|
|
|
|
|
|
This loader is enabled by default. However it won't find any templates
|
|
|
|
|
until you set :setting:`DIRS <TEMPLATES-DIRS>` to a non-empty list::
|
|
|
|
|
|
|
|
|
|
TEMPLATES = [{
|
|
|
|
|
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
|
|
|
|
'DIRS': [os.path.join(BASE_DIR, 'templates')],
|
|
|
|
|
}]
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2009-12-14 12:08:23 +00:00
|
|
|
|
``django.template.loaders.app_directories.Loader``
|
2013-01-01 13:12:42 +00:00
|
|
|
|
|
|
|
|
|
.. class:: app_directories.Loader
|
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
Loads templates from Django apps on the filesystem. For each app in
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 18:30:54 +00:00
|
|
|
|
:setting:`INSTALLED_APPS`, the loader looks for a ``templates``
|
|
|
|
|
subdirectory. If the directory exists, Django looks for templates in there.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
|
|
This means you can store templates with your individual apps. This also
|
|
|
|
|
makes it easy to distribute Django apps with default templates.
|
|
|
|
|
|
|
|
|
|
For example, for this setting::
|
|
|
|
|
|
|
|
|
|
INSTALLED_APPS = ('myproject.polls', 'myproject.music')
|
|
|
|
|
|
2012-07-12 21:02:58 +00:00
|
|
|
|
...then ``get_template('foo.html')`` will look for ``foo.html`` in these
|
2008-08-23 22:25:40 +00:00
|
|
|
|
directories, in this order:
|
|
|
|
|
|
2012-07-12 21:02:58 +00:00
|
|
|
|
* ``/path/to/myproject/polls/templates/``
|
|
|
|
|
* ``/path/to/myproject/music/templates/``
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2012-07-12 21:02:58 +00:00
|
|
|
|
... and will use the one it finds first.
|
|
|
|
|
|
|
|
|
|
The order of :setting:`INSTALLED_APPS` is significant! For example, if you
|
|
|
|
|
want to customize the Django admin, you might choose to override the
|
|
|
|
|
standard ``admin/base_site.html`` template, from ``django.contrib.admin``,
|
|
|
|
|
with your own ``admin/base_site.html`` in ``myproject.polls``. You must
|
|
|
|
|
then make sure that your ``myproject.polls`` comes *before*
|
|
|
|
|
``django.contrib.admin`` in :setting:`INSTALLED_APPS`, otherwise
|
2013-08-05 16:23:26 +00:00
|
|
|
|
``django.contrib.admin``’s will be loaded first and yours will be ignored.
|
2012-07-12 21:02:58 +00:00
|
|
|
|
|
2014-11-16 23:13:40 +00:00
|
|
|
|
Note that the loader performs an optimization when it first runs:
|
2012-07-12 21:02:58 +00:00
|
|
|
|
it caches a list of which :setting:`INSTALLED_APPS` packages have a
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 18:30:54 +00:00
|
|
|
|
``templates`` subdirectory.
|
2009-07-16 16:16:13 +00:00
|
|
|
|
|
2014-12-17 21:10:57 +00:00
|
|
|
|
This loader is enabled if and only if :setting:`APP_DIRS
|
|
|
|
|
<TEMPLATES-APP_DIRS>` is set::
|
|
|
|
|
|
|
|
|
|
TEMPLATES = [{
|
|
|
|
|
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
|
|
|
|
'APP_DIRS': True,
|
|
|
|
|
}]
|
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2009-12-14 12:08:23 +00:00
|
|
|
|
``django.template.loaders.eggs.Loader``
|
2013-01-01 13:12:42 +00:00
|
|
|
|
|
|
|
|
|
.. class:: eggs.Loader
|
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
Just like ``app_directories`` above, but it loads templates from Python
|
|
|
|
|
eggs rather than from the filesystem.
|
2009-07-16 16:16:13 +00:00
|
|
|
|
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 18:30:54 +00:00
|
|
|
|
This loader is disabled by default.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2009-12-14 12:08:23 +00:00
|
|
|
|
``django.template.loaders.cached.Loader``
|
2013-01-01 13:12:42 +00:00
|
|
|
|
|
|
|
|
|
.. class:: cached.Loader
|
|
|
|
|
|
2009-12-14 12:08:23 +00:00
|
|
|
|
By default, the templating system will read and compile your templates every
|
|
|
|
|
time they need to be rendered. While the Django templating system is quite
|
|
|
|
|
fast, the overhead from reading and compiling templates can add up.
|
|
|
|
|
|
|
|
|
|
The cached template loader is a class-based loader that you configure with
|
|
|
|
|
a list of other loaders that it should wrap. The wrapped loaders are used to
|
|
|
|
|
locate unknown templates when they are first encountered. The cached loader
|
|
|
|
|
then stores the compiled ``Template`` in memory. The cached ``Template``
|
|
|
|
|
instance is returned for subsequent requests to load the same template.
|
|
|
|
|
|
|
|
|
|
For example, to enable template caching with the ``filesystem`` and
|
|
|
|
|
``app_directories`` template loaders you might use the following settings::
|
|
|
|
|
|
2014-12-17 21:10:57 +00:00
|
|
|
|
TEMPLATES = [{
|
|
|
|
|
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
|
|
|
|
'DIRS': [os.path.join(BASE_DIR, 'templates')],
|
|
|
|
|
'OPTIONS': {
|
|
|
|
|
'loaders': [
|
|
|
|
|
('django.template.loaders.cached.Loader', (
|
|
|
|
|
'django.template.loaders.filesystem.Loader',
|
|
|
|
|
'django.template.loaders.app_directories.Loader',
|
|
|
|
|
)),
|
|
|
|
|
],
|
|
|
|
|
},
|
|
|
|
|
}]
|
2009-12-14 12:08:23 +00:00
|
|
|
|
|
|
|
|
|
.. note::
|
2011-09-16 18:06:42 +00:00
|
|
|
|
|
|
|
|
|
All of the built-in Django template tags are safe to use with the
|
|
|
|
|
cached loader, but if you're using custom template tags that come from
|
|
|
|
|
third party packages, or that you wrote yourself, you should ensure
|
|
|
|
|
that the ``Node`` implementation for each tag is thread-safe. For more
|
|
|
|
|
information, see :ref:`template tag thread safety
|
|
|
|
|
considerations<template_tag_thread_safety>`.
|
2009-12-14 12:08:23 +00:00
|
|
|
|
|
|
|
|
|
This loader is disabled by default.
|
|
|
|
|
|
2014-11-16 23:13:40 +00:00
|
|
|
|
``django.template.loaders.locmem.Loader``
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 1.8
|
|
|
|
|
|
|
|
|
|
.. class:: locmem.Loader
|
|
|
|
|
|
|
|
|
|
Loads templates from a Python dictionary. This is useful for testing.
|
|
|
|
|
|
|
|
|
|
This loader takes a dictionary of templates as its first argument::
|
|
|
|
|
|
2014-12-17 21:10:57 +00:00
|
|
|
|
TEMPLATES = [{
|
|
|
|
|
'BACKEND': 'django.template.backends.django.DjangoTemplates',
|
|
|
|
|
'OPTIONS': {
|
|
|
|
|
'loaders': [
|
|
|
|
|
('django.template.loaders.locmem.Loader', {
|
|
|
|
|
'index.html': 'content here',
|
|
|
|
|
}),
|
|
|
|
|
],
|
|
|
|
|
},
|
|
|
|
|
}]
|
2014-11-16 23:13:40 +00:00
|
|
|
|
|
|
|
|
|
This loader is disabled by default.
|
|
|
|
|
|
2014-12-17 21:10:57 +00:00
|
|
|
|
Django uses the template loaders in order according to the ``'loaders'``
|
|
|
|
|
option. It uses each loader until a loader finds a match.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2013-08-30 19:08:40 +00:00
|
|
|
|
.. currentmodule:: django.template
|
|
|
|
|
|
|
|
|
|
Template origin
|
|
|
|
|
~~~~~~~~~~~~~~~
|
|
|
|
|
|
|
|
|
|
.. versionadded:: 1.7
|
|
|
|
|
|
|
|
|
|
When :setting:`TEMPLATE_DEBUG` is ``True`` template objects will have an
|
|
|
|
|
``origin`` attribute depending on the source they are loaded from.
|
|
|
|
|
|
|
|
|
|
.. class:: loader.LoaderOrigin
|
|
|
|
|
|
|
|
|
|
Templates created from a template loader will use the
|
|
|
|
|
``django.template.loader.LoaderOrigin`` class.
|
|
|
|
|
|
|
|
|
|
.. attribute:: name
|
|
|
|
|
|
|
|
|
|
The path to the template as returned by the template loader.
|
|
|
|
|
For loaders that read from the file system, this is the full
|
|
|
|
|
path to the template.
|
|
|
|
|
|
|
|
|
|
.. attribute:: loadname
|
|
|
|
|
|
|
|
|
|
The relative path to the template as passed into the
|
|
|
|
|
template loader.
|
|
|
|
|
|
|
|
|
|
.. class:: StringOrigin
|
|
|
|
|
|
|
|
|
|
Templates created from a ``Template`` class will use the
|
|
|
|
|
``django.template.StringOrigin`` class.
|
|
|
|
|
|
|
|
|
|
.. attribute:: source
|
|
|
|
|
|
|
|
|
|
The string used to create the template.
|
|
|
|
|
|
2010-11-29 00:55:04 +00:00
|
|
|
|
The ``render_to_string`` shortcut
|
2008-08-23 22:25:40 +00:00
|
|
|
|
===================================
|
|
|
|
|
|
2014-11-28 22:50:34 +00:00
|
|
|
|
.. function:: loader.render_to_string(template_name, context=None, context_instance=None)
|
2010-11-29 00:55:04 +00:00
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
To cut down on the repetitive nature of loading and rendering
|
|
|
|
|
templates, Django provides a shortcut function which largely
|
|
|
|
|
automates the process: ``render_to_string()`` in
|
2010-11-29 00:55:04 +00:00
|
|
|
|
:mod:`django.template.loader`, which loads a template, renders it and
|
2008-08-23 22:25:40 +00:00
|
|
|
|
returns the resulting string::
|
|
|
|
|
|
|
|
|
|
from django.template.loader import render_to_string
|
2012-04-20 01:31:07 +00:00
|
|
|
|
rendered = render_to_string('my_template.html', {'foo': 'bar'})
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
|
|
|
|
The ``render_to_string`` shortcut takes one required argument --
|
|
|
|
|
``template_name``, which should be the name of the template to load
|
2010-01-10 17:22:30 +00:00
|
|
|
|
and render (or a list of template names, in which case Django will use
|
|
|
|
|
the first template in the list that exists) -- and two optional arguments:
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-11-28 22:50:34 +00:00
|
|
|
|
``context``
|
2011-10-14 00:12:01 +00:00
|
|
|
|
A dictionary to be used as variables and values for the
|
2014-11-28 22:50:34 +00:00
|
|
|
|
template's context. This should be passed as the second
|
2011-10-14 00:12:01 +00:00
|
|
|
|
positional argument.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-11-28 22:50:34 +00:00
|
|
|
|
.. versionchanged:: 1.8
|
|
|
|
|
|
|
|
|
|
The ``context`` argument used to be called ``dictionary``. That name
|
|
|
|
|
is deprecated in Django 1.8 and will be removed in Django 2.0.
|
|
|
|
|
|
|
|
|
|
``context_instance``
|
2013-12-15 22:02:20 +00:00
|
|
|
|
An instance of :class:`~django.template.Context` or a subclass (e.g., an
|
|
|
|
|
instance of :class:`~django.template.RequestContext`) to use as the
|
|
|
|
|
template's context. This can also be passed as the third positional argument.
|
2008-08-23 22:25:40 +00:00
|
|
|
|
|
2014-11-28 22:50:34 +00:00
|
|
|
|
.. deprecated:: 1.8
|
|
|
|
|
|
|
|
|
|
The ``context_instance`` argument is deprecated. Simply use ``context``.
|
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
|
See also the :func:`~django.shortcuts.render_to_response()` shortcut, which
|
2010-11-29 00:55:04 +00:00
|
|
|
|
calls ``render_to_string`` and feeds the result into an :class:`~django.http.HttpResponse`
|
2008-08-23 22:25:40 +00:00
|
|
|
|
suitable for returning directly from a view.
|
|
|
|
|
|
|
|
|
|
Configuring the template system in standalone mode
|
|
|
|
|
==================================================
|
|
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
|
|
|
|
|
This section is only of interest to people trying to use the template
|
|
|
|
|
system as an output component in another application. If you're using the
|
|
|
|
|
template system as part of a Django application, nothing here applies to
|
|
|
|
|
you.
|
|
|
|
|
|
|
|
|
|
Normally, Django will load all the configuration information it needs from its
|
|
|
|
|
own default configuration file, combined with the settings in the module given
|
2010-08-23 08:07:35 +00:00
|
|
|
|
in the :envvar:`DJANGO_SETTINGS_MODULE` environment variable. But if you're
|
2008-08-23 22:25:40 +00:00
|
|
|
|
using the template system independently of the rest of Django, the environment
|
|
|
|
|
variable approach isn't very convenient, because you probably want to configure
|
|
|
|
|
the template system in line with the rest of your application rather than
|
|
|
|
|
dealing with settings files and pointing to them via environment variables.
|
|
|
|
|
|
|
|
|
|
To solve this problem, you need to use the manual configuration option described
|
|
|
|
|
in :ref:`settings-without-django-settings-module`. Simply import the appropriate
|
|
|
|
|
pieces of the templating system and then, *before* you call any of the
|
2010-11-29 00:55:04 +00:00
|
|
|
|
templating functions, call :func:`django.conf.settings.configure()` with any
|
2008-08-23 22:25:40 +00:00
|
|
|
|
settings you wish to specify. You might want to consider setting at least
|
2014-12-17 21:51:42 +00:00
|
|
|
|
:setting:`DIRS <TEMPLATES-DIRS>` (if you're going to use template loaders),
|
2008-08-23 22:25:40 +00:00
|
|
|
|
:setting:`DEFAULT_CHARSET` (although the default of ``utf-8`` is probably fine)
|
2012-06-02 09:35:36 +00:00
|
|
|
|
and :setting:`TEMPLATE_DEBUG`. If you plan to use the :ttag:`url` template tag,
|
|
|
|
|
you will also need to set the :setting:`ROOT_URLCONF` setting. All available
|
|
|
|
|
settings are described in the :doc:`settings documentation </ref/settings>`,
|
|
|
|
|
and any setting starting with ``TEMPLATE_`` is of obvious interest.
|
2009-12-14 12:08:23 +00:00
|
|
|
|
|
|
|
|
|
.. _topic-template-alternate-language:
|
|
|
|
|
|
|
|
|
|
Using an alternative template language
|
|
|
|
|
======================================
|
|
|
|
|
|
|
|
|
|
The Django ``Template`` and ``Loader`` classes implement a simple API for
|
|
|
|
|
loading and rendering templates. By providing some simple wrapper classes that
|
|
|
|
|
implement this API we can use third party template systems like `Jinja2
|
2014-09-21 15:30:18 +00:00
|
|
|
|
<http://jinja.pocoo.org/docs/>`_. This
|
2009-12-14 12:08:23 +00:00
|
|
|
|
allows us to use third-party template libraries without giving up useful Django
|
|
|
|
|
features like the Django ``Context`` object and handy shortcuts like
|
2011-05-21 18:36:01 +00:00
|
|
|
|
:func:`~django.shortcuts.render_to_response()`.
|
2009-12-14 12:08:23 +00:00
|
|
|
|
|
|
|
|
|
The core component of the Django templating system is the ``Template`` class.
|
|
|
|
|
This class has a very simple interface: it has a constructor that takes a single
|
|
|
|
|
positional argument specifying the template string, and a ``render()`` method
|
2010-11-29 00:55:04 +00:00
|
|
|
|
that takes a :class:`~django.template.Context` object and returns a string
|
2009-12-14 12:08:23 +00:00
|
|
|
|
containing the rendered response.
|
|
|
|
|
|
|
|
|
|
Suppose we're using a template language that defines a ``Template`` object with
|
|
|
|
|
a ``render()`` method that takes a dictionary rather than a ``Context`` object.
|
|
|
|
|
We can write a simple wrapper that implements the Django ``Template`` interface::
|
|
|
|
|
|
|
|
|
|
import some_template_language
|
|
|
|
|
class Template(some_template_language.Template):
|
|
|
|
|
def render(self, context):
|
|
|
|
|
# flatten the Django Context into a single dictionary.
|
|
|
|
|
context_dict = {}
|
|
|
|
|
for d in context.dicts:
|
|
|
|
|
context_dict.update(d)
|
|
|
|
|
return super(Template, self).render(context_dict)
|
|
|
|
|
|
|
|
|
|
That's all that's required to make our fictional ``Template`` class compatible
|
|
|
|
|
with the Django loading and rendering system!
|
|
|
|
|
|
|
|
|
|
The next step is to write a ``Loader`` class that returns instances of our custom
|
2010-11-29 00:55:04 +00:00
|
|
|
|
template class instead of the default :class:`~django.template.Template`. Custom ``Loader``
|
2014-11-15 17:35:02 +00:00
|
|
|
|
classes should inherit from ``django.template.loaders.base.Loader`` and override
|
2009-12-14 12:08:23 +00:00
|
|
|
|
the ``load_template_source()`` method, which takes a ``template_name`` argument,
|
|
|
|
|
loads the template from disk (or elsewhere), and returns a tuple:
|
|
|
|
|
``(template_string, template_origin)``.
|
|
|
|
|
|
2014-11-15 17:35:02 +00:00
|
|
|
|
.. versionchanged:: 1.8
|
|
|
|
|
|
|
|
|
|
``django.template.loaders.base.Loader`` used to be defined at
|
|
|
|
|
``django.template.loader.BaseLoader``.
|
|
|
|
|
|
2009-12-14 12:08:23 +00:00
|
|
|
|
The ``load_template()`` method of the ``Loader`` class retrieves the template
|
|
|
|
|
string by calling ``load_template_source()``, instantiates a ``Template`` from
|
|
|
|
|
the template source, and returns a tuple: ``(template, template_origin)``. Since
|
|
|
|
|
this is the method that actually instantiates the ``Template``, we'll need to
|
|
|
|
|
override it to use our custom template class instead. We can inherit from the
|
2010-11-29 00:55:04 +00:00
|
|
|
|
builtin :class:`django.template.loaders.app_directories.Loader` to take advantage
|
|
|
|
|
of the ``load_template_source()`` method implemented there::
|
2009-12-14 12:08:23 +00:00
|
|
|
|
|
|
|
|
|
from django.template.loaders import app_directories
|
|
|
|
|
class Loader(app_directories.Loader):
|
|
|
|
|
is_usable = True
|
|
|
|
|
|
|
|
|
|
def load_template(self, template_name, template_dirs=None):
|
|
|
|
|
source, origin = self.load_template_source(template_name, template_dirs)
|
|
|
|
|
template = Template(source)
|
|
|
|
|
return template, origin
|
|
|
|
|
|
|
|
|
|
Finally, we need to modify our project settings, telling Django to use our custom
|
|
|
|
|
loader. Now we can write all of our templates in our alternative template
|
|
|
|
|
language while continuing to use the rest of the Django templating system.
|