api.txt 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. ====================================================
  2. The Django template language: For Python programmers
  3. ====================================================
  4. .. module:: django.template
  5. :synopsis: Django's template system
  6. This document explains the Django template system from a technical
  7. perspective -- how it works and how to extend it. If you're just looking for
  8. reference on the language syntax, see :doc:`/topics/templates`.
  9. If you're looking to use the Django template system as part of another
  10. application -- i.e., without the rest of the framework -- make sure to read
  11. the `configuration`_ section later in this document.
  12. .. _configuration: `configuring the template system in standalone mode`_
  13. Basics
  14. ======
  15. A **template** is a text document, or a normal Python string, that is marked-up
  16. using the Django template language. A template can contain **block tags** or
  17. **variables**.
  18. A **block tag** is a symbol within a template that does something.
  19. This definition is deliberately vague. For example, a block tag can output
  20. content, serve as a control structure (an "if" statement or "for" loop), grab
  21. content from a database or enable access to other template tags.
  22. Block tags are surrounded by ``"{%"`` and ``"%}"``.
  23. Example template with block tags:
  24. .. code-block:: html+django
  25. {% if is_logged_in %}Thanks for logging in!{% else %}Please log in.{% endif %}
  26. A **variable** is a symbol within a template that outputs a value.
  27. Variable tags are surrounded by ``"{{"`` and ``"}}"``.
  28. Example template with variables:
  29. .. code-block:: html+django
  30. My first name is {{ first_name }}. My last name is {{ last_name }}.
  31. A **context** is a "variable name" -> "variable value" mapping that is passed
  32. to a template.
  33. A template **renders** a context by replacing the variable "holes" with values
  34. from the context and executing all block tags.
  35. Using the template system
  36. =========================
  37. .. class:: Template
  38. Using the template system in Python is a two-step process:
  39. * First, you compile the raw template code into a ``Template`` object.
  40. * Then, you call the ``render()`` method of the ``Template`` object with a
  41. given context.
  42. Compiling a string
  43. ------------------
  44. The easiest way to create a ``Template`` object is by instantiating it
  45. directly. The class lives at :class:`django.template.Template`. The constructor
  46. takes one argument -- the raw template code::
  47. >>> from django.template import Template
  48. >>> t = Template("My name is {{ my_name }}.")
  49. >>> print(t)
  50. <django.template.Template instance>
  51. .. admonition:: Behind the scenes
  52. The system only parses your raw template code once -- when you create the
  53. ``Template`` object. From then on, it's stored internally as a "node"
  54. structure for performance.
  55. Even the parsing itself is quite fast. Most of the parsing happens via a
  56. single call to a single, short, regular expression.
  57. Rendering a context
  58. -------------------
  59. .. method:: render(context)
  60. Once you have a compiled ``Template`` object, you can render a context -- or
  61. multiple contexts -- with it. The ``Context`` class lives at
  62. :class:`django.template.Context`, and the constructor takes two (optional)
  63. arguments:
  64. * A dictionary mapping variable names to variable values.
  65. * The name of the current application. This application name is used
  66. to help :ref:`resolve namespaced URLs<topics-http-reversing-url-namespaces>`.
  67. If you're not using namespaced URLs, you can ignore this argument.
  68. Call the ``Template`` object's ``render()`` method with the context to "fill" the
  69. template::
  70. >>> from django.template import Context, Template
  71. >>> t = Template("My name is {{ my_name }}.")
  72. >>> c = Context({"my_name": "Adrian"})
  73. >>> t.render(c)
  74. "My name is Adrian."
  75. >>> c = Context({"my_name": "Dolores"})
  76. >>> t.render(c)
  77. "My name is Dolores."
  78. Variables and lookups
  79. ~~~~~~~~~~~~~~~~~~~~~
  80. Variable names must consist of any letter (A-Z), any digit (0-9), an underscore
  81. (but they must not start with an underscore) or a dot.
  82. Dots have a special meaning in template rendering. A dot in a variable name
  83. signifies a **lookup**. Specifically, when the template system encounters a
  84. dot in a variable name, it tries the following lookups, in this order:
  85. * Dictionary lookup. Example: ``foo["bar"]``
  86. * Attribute lookup. Example: ``foo.bar``
  87. * List-index lookup. Example: ``foo[bar]``
  88. Note that "bar" in a template expression like ``{{ foo.bar }}`` will be
  89. interpreted as a literal string and not using the value of the variable "bar",
  90. if one exists in the template context.
  91. The template system uses the first lookup type that works. It's short-circuit
  92. logic. Here are a few examples::
  93. >>> from django.template import Context, Template
  94. >>> t = Template("My name is {{ person.first_name }}.")
  95. >>> d = {"person": {"first_name": "Joe", "last_name": "Johnson"}}
  96. >>> t.render(Context(d))
  97. "My name is Joe."
  98. >>> class PersonClass: pass
  99. >>> p = PersonClass()
  100. >>> p.first_name = "Ron"
  101. >>> p.last_name = "Nasty"
  102. >>> t.render(Context({"person": p}))
  103. "My name is Ron."
  104. >>> t = Template("The first stooge in the list is {{ stooges.0 }}.")
  105. >>> c = Context({"stooges": ["Larry", "Curly", "Moe"]})
  106. >>> t.render(c)
  107. "The first stooge in the list is Larry."
  108. If any part of the variable is callable, the template system will try calling
  109. it. Example::
  110. >>> class PersonClass2:
  111. ... def name(self):
  112. ... return "Samantha"
  113. >>> t = Template("My name is {{ person.name }}.")
  114. >>> t.render(Context({"person": PersonClass2}))
  115. "My name is Samantha."
  116. Callable variables are slightly more complex than variables which only require
  117. straight lookups. Here are some things to keep in mind:
  118. * If the variable raises an exception when called, the exception will be
  119. propagated, unless the exception has an attribute
  120. ``silent_variable_failure`` whose value is ``True``. If the exception
  121. *does* have a ``silent_variable_failure`` attribute whose value is
  122. ``True``, the variable will render as an empty string. Example::
  123. >>> t = Template("My name is {{ person.first_name }}.")
  124. >>> class PersonClass3:
  125. ... def first_name(self):
  126. ... raise AssertionError("foo")
  127. >>> p = PersonClass3()
  128. >>> t.render(Context({"person": p}))
  129. Traceback (most recent call last):
  130. ...
  131. AssertionError: foo
  132. >>> class SilentAssertionError(Exception):
  133. ... silent_variable_failure = True
  134. >>> class PersonClass4:
  135. ... def first_name(self):
  136. ... raise SilentAssertionError
  137. >>> p = PersonClass4()
  138. >>> t.render(Context({"person": p}))
  139. "My name is ."
  140. Note that :exc:`django.core.exceptions.ObjectDoesNotExist`, which is the
  141. base class for all Django database API ``DoesNotExist`` exceptions, has
  142. ``silent_variable_failure = True``. So if you're using Django templates
  143. with Django model objects, any ``DoesNotExist`` exception will fail
  144. silently.
  145. * A variable can only be called if it has no required arguments. Otherwise,
  146. the system will return an empty string.
  147. .. _alters-data-description:
  148. * Obviously, there can be side effects when calling some variables, and
  149. it'd be either foolish or a security hole to allow the template system
  150. to access them.
  151. A good example is the :meth:`~django.db.models.Model.delete` method on
  152. each Django model object. The template system shouldn't be allowed to do
  153. something like this::
  154. I will now delete this valuable data. {{ data.delete }}
  155. To prevent this, set an ``alters_data`` attribute on the callable
  156. variable. The template system won't call a variable if it has
  157. ``alters_data=True`` set, and will instead replace the variable with
  158. :setting:`TEMPLATE_STRING_IF_INVALID`, unconditionally. The
  159. dynamically-generated :meth:`~django.db.models.Model.delete` and
  160. :meth:`~django.db.models.Model.save` methods on Django model objects get
  161. ``alters_data=True`` automatically. Example::
  162. def sensitive_function(self):
  163. self.database_record.delete()
  164. sensitive_function.alters_data = True
  165. * Occasionally you may want to turn off this feature for other reasons,
  166. and tell the template system to leave a variable uncalled no matter
  167. what. To do so, set a ``do_not_call_in_templates`` attribute on the
  168. callable with the value ``True``. The template system then will act as
  169. if your variable is not callable (allowing you to access attributes of
  170. the callable, for example).
  171. .. _invalid-template-variables:
  172. How invalid variables are handled
  173. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  174. Generally, if a variable doesn't exist, the template system inserts the
  175. value of the :setting:`TEMPLATE_STRING_IF_INVALID` setting, which is set to
  176. ``''`` (the empty string) by default.
  177. Filters that are applied to an invalid variable will only be applied if
  178. :setting:`TEMPLATE_STRING_IF_INVALID` is set to ``''`` (the empty string). If
  179. :setting:`TEMPLATE_STRING_IF_INVALID` is set to any other value, variable
  180. filters will be ignored.
  181. This behavior is slightly different for the ``if``, ``for`` and ``regroup``
  182. template tags. If an invalid variable is provided to one of these template
  183. tags, the variable will be interpreted as ``None``. Filters are always
  184. applied to invalid variables within these template tags.
  185. If :setting:`TEMPLATE_STRING_IF_INVALID` contains a ``'%s'``, the format marker will
  186. be replaced with the name of the invalid variable.
  187. .. admonition:: For debug purposes only!
  188. While :setting:`TEMPLATE_STRING_IF_INVALID` can be a useful debugging tool,
  189. it is a bad idea to turn it on as a 'development default'.
  190. Many templates, including those in the Admin site, rely upon the
  191. silence of the template system when a non-existent variable is
  192. encountered. If you assign a value other than ``''`` to
  193. :setting:`TEMPLATE_STRING_IF_INVALID`, you will experience rendering
  194. problems with these templates and sites.
  195. Generally, :setting:`TEMPLATE_STRING_IF_INVALID` should only be enabled
  196. in order to debug a specific template problem, then cleared
  197. once debugging is complete.
  198. Builtin variables
  199. ~~~~~~~~~~~~~~~~~
  200. Every context contains ``True``, ``False`` and ``None``. As you would expect,
  201. these variables resolve to the corresponding Python objects.
  202. Limitations with string literals
  203. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  204. Django's template language has no way to escape the characters used for its own
  205. syntax. For example, the :ttag:`templatetag` tag is required if you need to
  206. output character sequences like ``{%`` and ``%}``.
  207. A similar issue exists if you want to include these sequences in template filter
  208. or tag arguments. For example, when parsing a block tag, Django's template
  209. parser looks for the first occurrence of ``%}`` after a ``{%``. This prevents
  210. the use of ``"%}"`` as a string literal. For example, a ``TemplateSyntaxError``
  211. will be raised for the following expressions::
  212. {% include "template.html" tvar="Some string literal with %} in it." %}
  213. {% with tvar="Some string literal with %} in it." %}{% endwith %}
  214. The same issue can be triggered by using a reserved sequence in filter
  215. arguments::
  216. {{ some.variable|default:"}}" }}
  217. If you need to use strings with these sequences, store them in template
  218. variables or use a custom template tag or filter to workaround the limitation.
  219. Playing with Context objects
  220. ----------------------------
  221. .. class:: Context
  222. Most of the time, you'll instantiate ``Context`` objects by passing in a
  223. fully-populated dictionary to ``Context()``. But you can add and delete items
  224. from a ``Context`` object once it's been instantiated, too, using standard
  225. dictionary syntax::
  226. >>> from django.template import Context
  227. >>> c = Context({"foo": "bar"})
  228. >>> c['foo']
  229. 'bar'
  230. >>> del c['foo']
  231. >>> c['foo']
  232. ''
  233. >>> c['newvariable'] = 'hello'
  234. >>> c['newvariable']
  235. 'hello'
  236. .. method:: Context.pop()
  237. .. method:: Context.push()
  238. .. exception:: ContextPopException
  239. A ``Context`` object is a stack. That is, you can ``push()`` and ``pop()`` it.
  240. If you ``pop()`` too much, it'll raise
  241. ``django.template.ContextPopException``::
  242. >>> c = Context()
  243. >>> c['foo'] = 'first level'
  244. >>> c.push()
  245. {}
  246. >>> c['foo'] = 'second level'
  247. >>> c['foo']
  248. 'second level'
  249. >>> c.pop()
  250. {'foo': 'second level'}
  251. >>> c['foo']
  252. 'first level'
  253. >>> c['foo'] = 'overwritten'
  254. >>> c['foo']
  255. 'overwritten'
  256. >>> c.pop()
  257. Traceback (most recent call last):
  258. ...
  259. ContextPopException
  260. .. versionadded:: 1.7
  261. You can also use ``push()`` as a context manager to ensure a matching ``pop()``
  262. is called.
  263. >>> c = Context()
  264. >>> c['foo'] = 'first level'
  265. >>> with c.push():
  266. >>> c['foo'] = 'second level'
  267. >>> c['foo']
  268. 'second level'
  269. >>> c['foo']
  270. 'first level'
  271. All arguments passed to ``push()`` will be passed to the ``dict`` constructor
  272. used to build the new context level.
  273. >>> c = Context()
  274. >>> c['foo'] = 'first level'
  275. >>> with c.push(foo='second level'):
  276. >>> c['foo']
  277. 'second level'
  278. >>> c['foo']
  279. 'first level'
  280. .. method:: update(other_dict)
  281. In addition to ``push()`` and ``pop()``, the ``Context``
  282. object also defines an ``update()`` method. This works like ``push()``
  283. but takes a dictionary as an argument and pushes that dictionary onto
  284. the stack instead of an empty one.
  285. >>> c = Context()
  286. >>> c['foo'] = 'first level'
  287. >>> c.update({'foo': 'updated'})
  288. {'foo': 'updated'}
  289. >>> c['foo']
  290. 'updated'
  291. >>> c.pop()
  292. {'foo': 'updated'}
  293. >>> c['foo']
  294. 'first level'
  295. Using a ``Context`` as a stack comes in handy in some custom template tags, as
  296. you'll see below.
  297. .. method:: Context.flatten()
  298. .. versionadded:: 1.7
  299. Using ``flatten()`` method you can get whole ``Context`` stack as one dictionary
  300. including builtin variables.
  301. >>> c = Context()
  302. >>> c['foo'] = 'first level'
  303. >>> c.update({'bar': 'second level'})
  304. {'bar': 'second level'}
  305. >>> c.flatten()
  306. {'True': True, 'None': None, 'foo': 'first level', 'False': False, 'bar': 'second level'}
  307. A ``flatten()`` method is also internally used to make ``Context`` objects comparable.
  308. >>> c1 = Context()
  309. >>> c1['foo'] = 'first level'
  310. >>> c1['bar'] = 'second level'
  311. >>> c2 = Context()
  312. >>> c2.update({'bar': 'second level', 'foo': 'first level'})
  313. {'foo': 'first level', 'bar': 'second level'}
  314. >>> c1 == c2
  315. True
  316. Result from ``flatten()`` can be useful in unit tests to compare ``Context``
  317. against ``dict``::
  318. class ContextTest(unittest.TestCase):
  319. def test_against_dictionary(self):
  320. c1 = Context()
  321. c1['update'] = 'value'
  322. self.assertEqual(c1.flatten(), {
  323. 'True': True, 'None': None, 'False': False,
  324. 'update': 'value'})
  325. .. _subclassing-context-requestcontext:
  326. Subclassing Context: RequestContext
  327. -----------------------------------
  328. .. class:: RequestContext
  329. Django comes with a special ``Context`` class,
  330. ``django.template.RequestContext``, that acts slightly differently than the
  331. normal ``django.template.Context``. The first difference is that it takes an
  332. :class:`~django.http.HttpRequest` as its first argument. For example::
  333. c = RequestContext(request, {
  334. 'foo': 'bar',
  335. })
  336. The second difference is that it automatically populates the context with a few
  337. variables, according to your :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting.
  338. The :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting is a tuple of callables --
  339. called **context processors** -- that take a request object as their argument
  340. and return a dictionary of items to be merged into the context. By default,
  341. :setting:`TEMPLATE_CONTEXT_PROCESSORS` is set to::
  342. ("django.contrib.auth.context_processors.auth",
  343. "django.core.context_processors.debug",
  344. "django.core.context_processors.i18n",
  345. "django.core.context_processors.media",
  346. "django.core.context_processors.static",
  347. "django.core.context_processors.tz",
  348. "django.contrib.messages.context_processors.messages")
  349. In addition to these, ``RequestContext`` always uses
  350. ``django.core.context_processors.csrf``. This is a security
  351. related context processor required by the admin and other contrib apps, and,
  352. in case of accidental misconfiguration, it is deliberately hardcoded in and
  353. cannot be turned off by the :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting.
  354. Each processor is applied in order. That means, if one processor adds a
  355. variable to the context and a second processor adds a variable with the same
  356. name, the second will override the first. The default processors are explained
  357. below.
  358. .. admonition:: When context processors are applied
  359. Context processors are applied *after* the context itself is processed.
  360. This means that a context processor may overwrite variables you've
  361. supplied to your ``Context`` or ``RequestContext``, so take care
  362. to avoid variable names that overlap with those supplied by your
  363. context processors.
  364. Also, you can give ``RequestContext`` a list of additional processors, using the
  365. optional, third positional argument, ``processors``. In this example, the
  366. ``RequestContext`` instance gets a ``ip_address`` variable::
  367. from django.http import HttpResponse
  368. from django.template import RequestContext
  369. def ip_address_processor(request):
  370. return {'ip_address': request.META['REMOTE_ADDR']}
  371. def some_view(request):
  372. # ...
  373. c = RequestContext(request, {
  374. 'foo': 'bar',
  375. }, [ip_address_processor])
  376. return HttpResponse(t.render(c))
  377. .. note::
  378. If you're using Django's :func:`~django.shortcuts.render_to_response()`
  379. shortcut to populate a template with the contents of a dictionary, your
  380. template will be passed a ``Context`` instance by default (not a
  381. ``RequestContext``). To use a ``RequestContext`` in your template
  382. rendering, pass an optional third argument to
  383. :func:`~django.shortcuts.render_to_response()`: a ``RequestContext``
  384. instance. Your code might look like this::
  385. from django.shortcuts import render_to_response
  386. from django.template import RequestContext
  387. def some_view(request):
  388. # ...
  389. return render_to_response('my_template.html',
  390. my_data_dictionary,
  391. context_instance=RequestContext(request))
  392. Alternatively, use the :meth:`~django.shortcuts.render()` shortcut which is
  393. the same as a call to :func:`~django.shortcuts.render_to_response()` with a
  394. context_instance argument that forces the use of a ``RequestContext``.
  395. Note that the contents of a supplied dictionary (``my_data_dictionary``
  396. in this example) will take precedence over any variables supplied by
  397. context processors or the ``RequestContext``.
  398. Here's what each of the default processors does:
  399. django.contrib.auth.context_processors.auth
  400. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  401. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  402. ``RequestContext`` will contain these variables:
  403. * ``user`` -- An ``auth.User`` instance representing the currently
  404. logged-in user (or an ``AnonymousUser`` instance, if the client isn't
  405. logged in).
  406. * ``perms`` -- An instance of
  407. ``django.contrib.auth.context_processors.PermWrapper``, representing the
  408. permissions that the currently logged-in user has.
  409. .. currentmodule:: django.core.context_processors
  410. django.core.context_processors.debug
  411. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  412. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  413. ``RequestContext`` will contain these two variables -- but only if your
  414. :setting:`DEBUG` setting is set to ``True`` and the request's IP address
  415. (``request.META['REMOTE_ADDR']``) is in the :setting:`INTERNAL_IPS` setting:
  416. * ``debug`` -- ``True``. You can use this in templates to test whether
  417. you're in :setting:`DEBUG` mode.
  418. * ``sql_queries`` -- A list of ``{'sql': ..., 'time': ...}`` dictionaries,
  419. representing every SQL query that has happened so far during the request
  420. and how long it took. The list is in order by query and lazily generated
  421. on access.
  422. django.core.context_processors.i18n
  423. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  424. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  425. ``RequestContext`` will contain these two variables:
  426. * ``LANGUAGES`` -- The value of the :setting:`LANGUAGES` setting.
  427. * ``LANGUAGE_CODE`` -- ``request.LANGUAGE_CODE``, if it exists. Otherwise,
  428. the value of the :setting:`LANGUAGE_CODE` setting.
  429. See :doc:`/topics/i18n/index` for more.
  430. django.core.context_processors.media
  431. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  432. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  433. ``RequestContext`` will contain a variable ``MEDIA_URL``, providing the
  434. value of the :setting:`MEDIA_URL` setting.
  435. django.core.context_processors.static
  436. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  437. .. function:: static
  438. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  439. ``RequestContext`` will contain a variable ``STATIC_URL``, providing the
  440. value of the :setting:`STATIC_URL` setting.
  441. django.core.context_processors.csrf
  442. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  443. This processor adds a token that is needed by the :ttag:`csrf_token` template
  444. tag for protection against :doc:`Cross Site Request Forgeries
  445. </ref/contrib/csrf>`.
  446. django.core.context_processors.request
  447. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  448. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  449. ``RequestContext`` will contain a variable ``request``, which is the current
  450. :class:`~django.http.HttpRequest`. Note that this processor is not enabled by default;
  451. you'll have to activate it.
  452. django.contrib.messages.context_processors.messages
  453. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  454. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  455. ``RequestContext`` will contain these two variables:
  456. * ``messages`` -- A list of messages (as strings) that have been set
  457. via the :doc:`messages framework </ref/contrib/messages>`.
  458. * ``DEFAULT_MESSAGE_LEVELS`` -- A mapping of the message level names to
  459. :ref:`their numeric value <message-level-constants>`.
  460. .. versionchanged:: 1.7
  461. The ``DEFAULT_MESSAGE_LEVELS`` variable was added.
  462. Writing your own context processors
  463. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  464. A context processor has a very simple interface: It's just a Python function
  465. that takes one argument, an :class:`~django.http.HttpRequest` object, and
  466. returns a dictionary that gets added to the template context. Each context
  467. processor *must* return a dictionary.
  468. Custom context processors can live anywhere in your code base. All Django cares
  469. about is that your custom context processors are pointed-to by your
  470. :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting.
  471. Loading templates
  472. -----------------
  473. Generally, you'll store templates in files on your filesystem rather than using
  474. the low-level ``Template`` API yourself. Save templates in a directory
  475. specified as a **template directory**.
  476. Django searches for template directories in a number of places, depending on
  477. your template-loader settings (see "Loader types" below), but the most basic
  478. way of specifying template directories is by using the :setting:`TEMPLATE_DIRS`
  479. setting.
  480. The TEMPLATE_DIRS setting
  481. ~~~~~~~~~~~~~~~~~~~~~~~~~
  482. Tell Django what your template directories are by using the
  483. :setting:`TEMPLATE_DIRS` setting in your settings file. This should be set to a
  484. list or tuple of strings that contain full paths to your template
  485. directory(ies). Example::
  486. TEMPLATE_DIRS = (
  487. "/home/html/templates/lawrence.com",
  488. "/home/html/templates/default",
  489. )
  490. Your templates can go anywhere you want, as long as the directories and
  491. templates are readable by the Web server. They can have any extension you want,
  492. such as ``.html`` or ``.txt``, or they can have no extension at all.
  493. Note that these paths should use Unix-style forward slashes, even on Windows.
  494. .. _ref-templates-api-the-python-api:
  495. The Python API
  496. ~~~~~~~~~~~~~~
  497. .. module:: django.template.loader
  498. ``django.template.loader`` has two functions to load templates from files:
  499. .. function:: get_template(template_name[, dirs])
  500. ``get_template`` returns the compiled template (a ``Template`` object) for
  501. the template with the given name. If the template doesn't exist, it raises
  502. ``django.template.TemplateDoesNotExist``.
  503. To override the :setting:`TEMPLATE_DIRS` setting, use the ``dirs``
  504. parameter. The ``dirs`` parameter may be a tuple or list.
  505. .. versionchanged:: 1.7
  506. The ``dirs`` parameter was added.
  507. .. function:: select_template(template_name_list[, dirs])
  508. ``select_template`` is just like ``get_template``, except it takes a list
  509. of template names. Of the list, it returns the first template that exists.
  510. To override the :setting:`TEMPLATE_DIRS` setting, use the ``dirs``
  511. parameter. The ``dirs`` parameter may be a tuple or list.
  512. .. versionchanged:: 1.7
  513. The ``dirs`` parameter was added.
  514. For example, if you call ``get_template('story_detail.html')`` and have the
  515. above :setting:`TEMPLATE_DIRS` setting, here are the files Django will look for,
  516. in order:
  517. * ``/home/html/templates/lawrence.com/story_detail.html``
  518. * ``/home/html/templates/default/story_detail.html``
  519. If you call ``select_template(['story_253_detail.html', 'story_detail.html'])``,
  520. here's what Django will look for:
  521. * ``/home/html/templates/lawrence.com/story_253_detail.html``
  522. * ``/home/html/templates/default/story_253_detail.html``
  523. * ``/home/html/templates/lawrence.com/story_detail.html``
  524. * ``/home/html/templates/default/story_detail.html``
  525. When Django finds a template that exists, it stops looking.
  526. .. admonition:: Tip
  527. You can use ``select_template()`` for super-flexible "templatability." For
  528. example, if you've written a news story and want some stories to have
  529. custom templates, use something like
  530. ``select_template(['story_%s_detail.html' % story.id, 'story_detail.html'])``.
  531. That'll allow you to use a custom template for an individual story, with a
  532. fallback template for stories that don't have custom templates.
  533. Using subdirectories
  534. ~~~~~~~~~~~~~~~~~~~~
  535. It's possible -- and preferable -- to organize templates in subdirectories of
  536. the template directory. The convention is to make a subdirectory for each
  537. Django app, with subdirectories within those subdirectories as needed.
  538. Do this for your own sanity. Storing all templates in the root level of a
  539. single directory gets messy.
  540. To load a template that's within a subdirectory, just use a slash, like so::
  541. get_template('news/story_detail.html')
  542. Using the same :setting:`TEMPLATE_DIRS` setting from above, this example
  543. ``get_template()`` call will attempt to load the following templates:
  544. * ``/home/html/templates/lawrence.com/news/story_detail.html``
  545. * ``/home/html/templates/default/news/story_detail.html``
  546. .. _template-loaders:
  547. Loader types
  548. ~~~~~~~~~~~~
  549. By default, Django uses a filesystem-based template loader, but Django comes
  550. with a few other template loaders, which know how to load templates from other
  551. sources.
  552. Some of these other loaders are disabled by default, but you can activate them
  553. by editing your :setting:`TEMPLATE_LOADERS` setting. :setting:`TEMPLATE_LOADERS`
  554. should be a tuple of strings, where each string represents a template loader
  555. class. Here are the template loaders that come with Django:
  556. .. currentmodule:: django.template.loaders
  557. ``django.template.loaders.filesystem.Loader``
  558. .. class:: filesystem.Loader
  559. Loads templates from the filesystem, according to :setting:`TEMPLATE_DIRS`.
  560. This loader is enabled by default.
  561. ``django.template.loaders.app_directories.Loader``
  562. .. class:: app_directories.Loader
  563. Loads templates from Django apps on the filesystem. For each app in
  564. :setting:`INSTALLED_APPS`, the loader looks for a ``templates``
  565. subdirectory. If the directory exists, Django looks for templates in there.
  566. This means you can store templates with your individual apps. This also
  567. makes it easy to distribute Django apps with default templates.
  568. For example, for this setting::
  569. INSTALLED_APPS = ('myproject.polls', 'myproject.music')
  570. ...then ``get_template('foo.html')`` will look for ``foo.html`` in these
  571. directories, in this order:
  572. * ``/path/to/myproject/polls/templates/``
  573. * ``/path/to/myproject/music/templates/``
  574. ... and will use the one it finds first.
  575. The order of :setting:`INSTALLED_APPS` is significant! For example, if you
  576. want to customize the Django admin, you might choose to override the
  577. standard ``admin/base_site.html`` template, from ``django.contrib.admin``,
  578. with your own ``admin/base_site.html`` in ``myproject.polls``. You must
  579. then make sure that your ``myproject.polls`` comes *before*
  580. ``django.contrib.admin`` in :setting:`INSTALLED_APPS`, otherwise
  581. ``django.contrib.admin``’s will be loaded first and yours will be ignored.
  582. Note that the loader performs an optimization when it is first imported:
  583. it caches a list of which :setting:`INSTALLED_APPS` packages have a
  584. ``templates`` subdirectory.
  585. This loader is enabled by default.
  586. ``django.template.loaders.eggs.Loader``
  587. .. class:: eggs.Loader
  588. Just like ``app_directories`` above, but it loads templates from Python
  589. eggs rather than from the filesystem.
  590. This loader is disabled by default.
  591. ``django.template.loaders.cached.Loader``
  592. .. class:: cached.Loader
  593. By default, the templating system will read and compile your templates every
  594. time they need to be rendered. While the Django templating system is quite
  595. fast, the overhead from reading and compiling templates can add up.
  596. The cached template loader is a class-based loader that you configure with
  597. a list of other loaders that it should wrap. The wrapped loaders are used to
  598. locate unknown templates when they are first encountered. The cached loader
  599. then stores the compiled ``Template`` in memory. The cached ``Template``
  600. instance is returned for subsequent requests to load the same template.
  601. For example, to enable template caching with the ``filesystem`` and
  602. ``app_directories`` template loaders you might use the following settings::
  603. TEMPLATE_LOADERS = (
  604. ('django.template.loaders.cached.Loader', (
  605. 'django.template.loaders.filesystem.Loader',
  606. 'django.template.loaders.app_directories.Loader',
  607. )),
  608. )
  609. .. note::
  610. All of the built-in Django template tags are safe to use with the
  611. cached loader, but if you're using custom template tags that come from
  612. third party packages, or that you wrote yourself, you should ensure
  613. that the ``Node`` implementation for each tag is thread-safe. For more
  614. information, see :ref:`template tag thread safety
  615. considerations<template_tag_thread_safety>`.
  616. This loader is disabled by default.
  617. Django uses the template loaders in order according to the
  618. :setting:`TEMPLATE_LOADERS` setting. It uses each loader until a loader finds a
  619. match.
  620. .. currentmodule:: django.template
  621. Template origin
  622. ~~~~~~~~~~~~~~~
  623. .. versionadded:: 1.7
  624. When :setting:`TEMPLATE_DEBUG` is ``True`` template objects will have an
  625. ``origin`` attribute depending on the source they are loaded from.
  626. .. class:: loader.LoaderOrigin
  627. Templates created from a template loader will use the
  628. ``django.template.loader.LoaderOrigin`` class.
  629. .. attribute:: name
  630. The path to the template as returned by the template loader.
  631. For loaders that read from the file system, this is the full
  632. path to the template.
  633. .. attribute:: loadname
  634. The relative path to the template as passed into the
  635. template loader.
  636. .. class:: StringOrigin
  637. Templates created from a ``Template`` class will use the
  638. ``django.template.StringOrigin`` class.
  639. .. attribute:: source
  640. The string used to create the template.
  641. The ``render_to_string`` shortcut
  642. ===================================
  643. .. function:: loader.render_to_string(template_name, dictionary=None, context_instance=None)
  644. To cut down on the repetitive nature of loading and rendering
  645. templates, Django provides a shortcut function which largely
  646. automates the process: ``render_to_string()`` in
  647. :mod:`django.template.loader`, which loads a template, renders it and
  648. returns the resulting string::
  649. from django.template.loader import render_to_string
  650. rendered = render_to_string('my_template.html', {'foo': 'bar'})
  651. The ``render_to_string`` shortcut takes one required argument --
  652. ``template_name``, which should be the name of the template to load
  653. and render (or a list of template names, in which case Django will use
  654. the first template in the list that exists) -- and two optional arguments:
  655. dictionary
  656. A dictionary to be used as variables and values for the
  657. template's context. This can also be passed as the second
  658. positional argument.
  659. context_instance
  660. An instance of :class:`~django.template.Context` or a subclass (e.g., an
  661. instance of :class:`~django.template.RequestContext`) to use as the
  662. template's context. This can also be passed as the third positional argument.
  663. See also the :func:`~django.shortcuts.render_to_response()` shortcut, which
  664. calls ``render_to_string`` and feeds the result into an :class:`~django.http.HttpResponse`
  665. suitable for returning directly from a view.
  666. Configuring the template system in standalone mode
  667. ==================================================
  668. .. note::
  669. This section is only of interest to people trying to use the template
  670. system as an output component in another application. If you're using the
  671. template system as part of a Django application, nothing here applies to
  672. you.
  673. Normally, Django will load all the configuration information it needs from its
  674. own default configuration file, combined with the settings in the module given
  675. in the :envvar:`DJANGO_SETTINGS_MODULE` environment variable. But if you're
  676. using the template system independently of the rest of Django, the environment
  677. variable approach isn't very convenient, because you probably want to configure
  678. the template system in line with the rest of your application rather than
  679. dealing with settings files and pointing to them via environment variables.
  680. To solve this problem, you need to use the manual configuration option described
  681. in :ref:`settings-without-django-settings-module`. Simply import the appropriate
  682. pieces of the templating system and then, *before* you call any of the
  683. templating functions, call :func:`django.conf.settings.configure()` with any
  684. settings you wish to specify. You might want to consider setting at least
  685. :setting:`TEMPLATE_DIRS` (if you're going to use template loaders),
  686. :setting:`DEFAULT_CHARSET` (although the default of ``utf-8`` is probably fine)
  687. and :setting:`TEMPLATE_DEBUG`. If you plan to use the :ttag:`url` template tag,
  688. you will also need to set the :setting:`ROOT_URLCONF` setting. All available
  689. settings are described in the :doc:`settings documentation </ref/settings>`,
  690. and any setting starting with ``TEMPLATE_`` is of obvious interest.
  691. .. _topic-template-alternate-language:
  692. Using an alternative template language
  693. ======================================
  694. The Django ``Template`` and ``Loader`` classes implement a simple API for
  695. loading and rendering templates. By providing some simple wrapper classes that
  696. implement this API we can use third party template systems like `Jinja2
  697. <http://jinja.pocoo.org/docs/>`_. This
  698. allows us to use third-party template libraries without giving up useful Django
  699. features like the Django ``Context`` object and handy shortcuts like
  700. :func:`~django.shortcuts.render_to_response()`.
  701. The core component of the Django templating system is the ``Template`` class.
  702. This class has a very simple interface: it has a constructor that takes a single
  703. positional argument specifying the template string, and a ``render()`` method
  704. that takes a :class:`~django.template.Context` object and returns a string
  705. containing the rendered response.
  706. Suppose we're using a template language that defines a ``Template`` object with
  707. a ``render()`` method that takes a dictionary rather than a ``Context`` object.
  708. We can write a simple wrapper that implements the Django ``Template`` interface::
  709. import some_template_language
  710. class Template(some_template_language.Template):
  711. def render(self, context):
  712. # flatten the Django Context into a single dictionary.
  713. context_dict = {}
  714. for d in context.dicts:
  715. context_dict.update(d)
  716. return super(Template, self).render(context_dict)
  717. That's all that's required to make our fictional ``Template`` class compatible
  718. with the Django loading and rendering system!
  719. The next step is to write a ``Loader`` class that returns instances of our custom
  720. template class instead of the default :class:`~django.template.Template`. Custom ``Loader``
  721. classes should inherit from ``django.template.loader.BaseLoader`` and override
  722. the ``load_template_source()`` method, which takes a ``template_name`` argument,
  723. loads the template from disk (or elsewhere), and returns a tuple:
  724. ``(template_string, template_origin)``.
  725. The ``load_template()`` method of the ``Loader`` class retrieves the template
  726. string by calling ``load_template_source()``, instantiates a ``Template`` from
  727. the template source, and returns a tuple: ``(template, template_origin)``. Since
  728. this is the method that actually instantiates the ``Template``, we'll need to
  729. override it to use our custom template class instead. We can inherit from the
  730. builtin :class:`django.template.loaders.app_directories.Loader` to take advantage
  731. of the ``load_template_source()`` method implemented there::
  732. from django.template.loaders import app_directories
  733. class Loader(app_directories.Loader):
  734. is_usable = True
  735. def load_template(self, template_name, template_dirs=None):
  736. source, origin = self.load_template_source(template_name, template_dirs)
  737. template = Template(source)
  738. return template, origin
  739. Finally, we need to modify our project settings, telling Django to use our custom
  740. loader. Now we can write all of our templates in our alternative template
  741. language while continuing to use the rest of the Django templating system.