api.txt 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886
  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 un-called 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. Playing with Context objects
  203. ----------------------------
  204. .. class:: Context
  205. Most of the time, you'll instantiate ``Context`` objects by passing in a
  206. fully-populated dictionary to ``Context()``. But you can add and delete items
  207. from a ``Context`` object once it's been instantiated, too, using standard
  208. dictionary syntax::
  209. >>> from django.template import Context
  210. >>> c = Context({"foo": "bar"})
  211. >>> c['foo']
  212. 'bar'
  213. >>> del c['foo']
  214. >>> c['foo']
  215. ''
  216. >>> c['newvariable'] = 'hello'
  217. >>> c['newvariable']
  218. 'hello'
  219. .. method:: Context.pop()
  220. .. method:: Context.push()
  221. .. exception:: ContextPopException
  222. A ``Context`` object is a stack. That is, you can ``push()`` and ``pop()`` it.
  223. If you ``pop()`` too much, it'll raise
  224. ``django.template.ContextPopException``::
  225. >>> c = Context()
  226. >>> c['foo'] = 'first level'
  227. >>> c.push()
  228. >>> c['foo'] = 'second level'
  229. >>> c['foo']
  230. 'second level'
  231. >>> c.pop()
  232. >>> c['foo']
  233. 'first level'
  234. >>> c['foo'] = 'overwritten'
  235. >>> c['foo']
  236. 'overwritten'
  237. >>> c.pop()
  238. Traceback (most recent call last):
  239. ...
  240. django.template.ContextPopException
  241. .. versionadded:: 1.7
  242. You can also use ``push()`` as a context manager to ensure a matching ``pop()``
  243. is called.
  244. >>> c = Context()
  245. >>> c['foo'] = 'first level'
  246. >>> with c.push():
  247. >>> c['foo'] = 'second level'
  248. >>> c['foo']
  249. 'second level'
  250. >>> c['foo']
  251. 'first level'
  252. All arguments passed to ``push()`` will be passed to the ``dict`` constructor
  253. used to build the new context level.
  254. >>> c = Context()
  255. >>> c['foo'] = 'first level'
  256. >>> with c.push(foo='second level'):
  257. >>> c['foo']
  258. 'second level'
  259. >>> c['foo']
  260. 'first level'
  261. .. method:: update(other_dict)
  262. In addition to ``push()`` and ``pop()``, the ``Context``
  263. object also defines an ``update()`` method. This works like ``push()``
  264. but takes a dictionary as an argument and pushes that dictionary onto
  265. the stack instead of an empty one.
  266. >>> c = Context()
  267. >>> c['foo'] = 'first level'
  268. >>> c.update({'foo': 'updated'})
  269. {'foo': 'updated'}
  270. >>> c['foo']
  271. 'updated'
  272. >>> c.pop()
  273. {'foo': 'updated'}
  274. >>> c['foo']
  275. 'first level'
  276. Using a ``Context`` as a stack comes in handy in some custom template tags, as
  277. you'll see below.
  278. .. _subclassing-context-requestcontext:
  279. Subclassing Context: RequestContext
  280. -----------------------------------
  281. .. class:: RequestContext
  282. Django comes with a special ``Context`` class,
  283. ``django.template.RequestContext``, that acts slightly differently than the
  284. normal ``django.template.Context``. The first difference is that it takes an
  285. :class:`~django.http.HttpRequest` as its first argument. For example::
  286. c = RequestContext(request, {
  287. 'foo': 'bar',
  288. })
  289. The second difference is that it automatically populates the context with a few
  290. variables, according to your :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting.
  291. The :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting is a tuple of callables --
  292. called **context processors** -- that take a request object as their argument
  293. and return a dictionary of items to be merged into the context. By default,
  294. :setting:`TEMPLATE_CONTEXT_PROCESSORS` is set to::
  295. ("django.contrib.auth.context_processors.auth",
  296. "django.core.context_processors.debug",
  297. "django.core.context_processors.i18n",
  298. "django.core.context_processors.media",
  299. "django.core.context_processors.static",
  300. "django.core.context_processors.tz",
  301. "django.contrib.messages.context_processors.messages")
  302. In addition to these, ``RequestContext`` always uses
  303. ``django.core.context_processors.csrf``. This is a security
  304. related context processor required by the admin and other contrib apps, and,
  305. in case of accidental misconfiguration, it is deliberately hardcoded in and
  306. cannot be turned off by the :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting.
  307. Each processor is applied in order. That means, if one processor adds a
  308. variable to the context and a second processor adds a variable with the same
  309. name, the second will override the first. The default processors are explained
  310. below.
  311. .. admonition:: When context processors are applied
  312. When you use ``RequestContext``, the variables you supply directly
  313. are added first, followed any variables supplied by context
  314. processors. This means that a context processor may overwrite a
  315. variable you've supplied, so take care to avoid variable names
  316. which overlap with those supplied by your context processors.
  317. Also, you can give ``RequestContext`` a list of additional processors, using the
  318. optional, third positional argument, ``processors``. In this example, the
  319. ``RequestContext`` instance gets a ``ip_address`` variable::
  320. from django.http import HttpResponse
  321. from django.template import RequestContext
  322. def ip_address_processor(request):
  323. return {'ip_address': request.META['REMOTE_ADDR']}
  324. def some_view(request):
  325. # ...
  326. c = RequestContext(request, {
  327. 'foo': 'bar',
  328. }, [ip_address_processor])
  329. return HttpResponse(t.render(c))
  330. .. note::
  331. If you're using Django's :func:`~django.shortcuts.render_to_response()`
  332. shortcut to populate a template with the contents of a dictionary, your
  333. template will be passed a ``Context`` instance by default (not a
  334. ``RequestContext``). To use a ``RequestContext`` in your template
  335. rendering, pass an optional third argument to
  336. :func:`~django.shortcuts.render_to_response()`: a ``RequestContext``
  337. instance. Your code might look like this::
  338. from django.shortcuts import render_to_response
  339. from django.template import RequestContext
  340. def some_view(request):
  341. # ...
  342. return render_to_response('my_template.html',
  343. my_data_dictionary,
  344. context_instance=RequestContext(request))
  345. Alternatively, use the :meth:`~django.shortcuts.render()` shortcut which is
  346. the same as a call to :func:`~django.shortcuts.render_to_response()` with a
  347. context_instance argument that forces the use of a ``RequestContext``.
  348. Here's what each of the default processors does:
  349. django.contrib.auth.context_processors.auth
  350. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  351. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  352. ``RequestContext`` will contain these variables:
  353. * ``user`` -- An ``auth.User`` instance representing the currently
  354. logged-in user (or an ``AnonymousUser`` instance, if the client isn't
  355. logged in).
  356. * ``perms`` -- An instance of
  357. ``django.contrib.auth.context_processors.PermWrapper``, representing the
  358. permissions that the currently logged-in user has.
  359. .. currentmodule:: django.core.context_processors
  360. django.core.context_processors.debug
  361. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  362. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  363. ``RequestContext`` will contain these two variables -- but only if your
  364. :setting:`DEBUG` setting is set to ``True`` and the request's IP address
  365. (``request.META['REMOTE_ADDR']``) is in the :setting:`INTERNAL_IPS` setting:
  366. * ``debug`` -- ``True``. You can use this in templates to test whether
  367. you're in :setting:`DEBUG` mode.
  368. * ``sql_queries`` -- A list of ``{'sql': ..., 'time': ...}`` dictionaries,
  369. representing every SQL query that has happened so far during the request
  370. and how long it took. The list is in order by query.
  371. django.core.context_processors.i18n
  372. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  373. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  374. ``RequestContext`` will contain these two variables:
  375. * ``LANGUAGES`` -- The value of the :setting:`LANGUAGES` setting.
  376. * ``LANGUAGE_CODE`` -- ``request.LANGUAGE_CODE``, if it exists. Otherwise,
  377. the value of the :setting:`LANGUAGE_CODE` setting.
  378. See :doc:`/topics/i18n/index` for more.
  379. django.core.context_processors.media
  380. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  381. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  382. ``RequestContext`` will contain a variable ``MEDIA_URL``, providing the
  383. value of the :setting:`MEDIA_URL` setting.
  384. django.core.context_processors.static
  385. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  386. .. function:: static
  387. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  388. ``RequestContext`` will contain a variable ``STATIC_URL``, providing the
  389. value of the :setting:`STATIC_URL` setting.
  390. django.core.context_processors.csrf
  391. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  392. This processor adds a token that is needed by the :ttag:`csrf_token` template
  393. tag for protection against :doc:`Cross Site Request Forgeries
  394. </ref/contrib/csrf>`.
  395. django.core.context_processors.request
  396. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  397. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  398. ``RequestContext`` will contain a variable ``request``, which is the current
  399. :class:`~django.http.HttpRequest`. Note that this processor is not enabled by default;
  400. you'll have to activate it.
  401. django.contrib.messages.context_processors.messages
  402. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  403. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  404. ``RequestContext`` will contain a single additional variable:
  405. * ``messages`` -- A list of messages (as strings) that have been set
  406. via the user model (using ``user.message_set.create``) or through
  407. the :doc:`messages framework </ref/contrib/messages>`.
  408. Writing your own context processors
  409. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  410. A context processor has a very simple interface: It's just a Python function
  411. that takes one argument, an :class:`~django.http.HttpRequest` object, and
  412. returns a dictionary that gets added to the template context. Each context
  413. processor *must* return a dictionary.
  414. Custom context processors can live anywhere in your code base. All Django cares
  415. about is that your custom context processors are pointed-to by your
  416. :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting.
  417. Loading templates
  418. -----------------
  419. Generally, you'll store templates in files on your filesystem rather than using
  420. the low-level ``Template`` API yourself. Save templates in a directory
  421. specified as a **template directory**.
  422. Django searches for template directories in a number of places, depending on
  423. your template-loader settings (see "Loader types" below), but the most basic
  424. way of specifying template directories is by using the :setting:`TEMPLATE_DIRS`
  425. setting.
  426. The TEMPLATE_DIRS setting
  427. ~~~~~~~~~~~~~~~~~~~~~~~~~
  428. Tell Django what your template directories are by using the
  429. :setting:`TEMPLATE_DIRS` setting in your settings file. This should be set to a
  430. list or tuple of strings that contain full paths to your template
  431. directory(ies). Example::
  432. TEMPLATE_DIRS = (
  433. "/home/html/templates/lawrence.com",
  434. "/home/html/templates/default",
  435. )
  436. Your templates can go anywhere you want, as long as the directories and
  437. templates are readable by the Web server. They can have any extension you want,
  438. such as ``.html`` or ``.txt``, or they can have no extension at all.
  439. Note that these paths should use Unix-style forward slashes, even on Windows.
  440. .. _ref-templates-api-the-python-api:
  441. The Python API
  442. ~~~~~~~~~~~~~~
  443. .. module:: django.template.loader
  444. ``django.template.loader`` has two functions to load templates from files:
  445. .. function:: get_template(template_name)
  446. ``get_template`` returns the compiled template (a ``Template`` object) for
  447. the template with the given name. If the template doesn't exist, it raises
  448. ``django.template.TemplateDoesNotExist``.
  449. .. function:: select_template(template_name_list)
  450. ``select_template`` is just like ``get_template``, except it takes a list
  451. of template names. Of the list, it returns the first template that exists.
  452. For example, if you call ``get_template('story_detail.html')`` and have the
  453. above :setting:`TEMPLATE_DIRS` setting, here are the files Django will look for,
  454. in order:
  455. * ``/home/html/templates/lawrence.com/story_detail.html``
  456. * ``/home/html/templates/default/story_detail.html``
  457. If you call ``select_template(['story_253_detail.html', 'story_detail.html'])``,
  458. here's what Django will look for:
  459. * ``/home/html/templates/lawrence.com/story_253_detail.html``
  460. * ``/home/html/templates/default/story_253_detail.html``
  461. * ``/home/html/templates/lawrence.com/story_detail.html``
  462. * ``/home/html/templates/default/story_detail.html``
  463. When Django finds a template that exists, it stops looking.
  464. .. admonition:: Tip
  465. You can use ``select_template()`` for super-flexible "templatability." For
  466. example, if you've written a news story and want some stories to have
  467. custom templates, use something like
  468. ``select_template(['story_%s_detail.html' % story.id, 'story_detail.html'])``.
  469. That'll allow you to use a custom template for an individual story, with a
  470. fallback template for stories that don't have custom templates.
  471. Using subdirectories
  472. ~~~~~~~~~~~~~~~~~~~~
  473. It's possible -- and preferable -- to organize templates in subdirectories of
  474. the template directory. The convention is to make a subdirectory for each
  475. Django app, with subdirectories within those subdirectories as needed.
  476. Do this for your own sanity. Storing all templates in the root level of a
  477. single directory gets messy.
  478. To load a template that's within a subdirectory, just use a slash, like so::
  479. get_template('news/story_detail.html')
  480. Using the same :setting:`TEMPLATE_DIRS` setting from above, this example
  481. ``get_template()`` call will attempt to load the following templates:
  482. * ``/home/html/templates/lawrence.com/news/story_detail.html``
  483. * ``/home/html/templates/default/news/story_detail.html``
  484. .. _template-loaders:
  485. Loader types
  486. ~~~~~~~~~~~~
  487. By default, Django uses a filesystem-based template loader, but Django comes
  488. with a few other template loaders, which know how to load templates from other
  489. sources.
  490. Some of these other loaders are disabled by default, but you can activate them
  491. by editing your :setting:`TEMPLATE_LOADERS` setting. :setting:`TEMPLATE_LOADERS`
  492. should be a tuple of strings, where each string represents a template loader
  493. class. Here are the template loaders that come with Django:
  494. .. currentmodule:: django.template.loaders
  495. ``django.template.loaders.filesystem.Loader``
  496. .. class:: filesystem.Loader
  497. Loads templates from the filesystem, according to :setting:`TEMPLATE_DIRS`.
  498. This loader is enabled by default.
  499. ``django.template.loaders.app_directories.Loader``
  500. .. class:: app_directories.Loader
  501. Loads templates from Django apps on the filesystem. For each app in
  502. :setting:`INSTALLED_APPS`, the loader looks for a ``templates``
  503. subdirectory. If the directory exists, Django looks for templates in there.
  504. This means you can store templates with your individual apps. This also
  505. makes it easy to distribute Django apps with default templates.
  506. For example, for this setting::
  507. INSTALLED_APPS = ('myproject.polls', 'myproject.music')
  508. ...then ``get_template('foo.html')`` will look for ``foo.html`` in these
  509. directories, in this order:
  510. * ``/path/to/myproject/polls/templates/``
  511. * ``/path/to/myproject/music/templates/``
  512. ... and will use the one it finds first.
  513. The order of :setting:`INSTALLED_APPS` is significant! For example, if you
  514. want to customize the Django admin, you might choose to override the
  515. standard ``admin/base_site.html`` template, from ``django.contrib.admin``,
  516. with your own ``admin/base_site.html`` in ``myproject.polls``. You must
  517. then make sure that your ``myproject.polls`` comes *before*
  518. ``django.contrib.admin`` in :setting:`INSTALLED_APPS`, otherwise
  519. ``django.contrib.admin``’s will be loaded first and yours will be ignored.
  520. Note that the loader performs an optimization when it is first imported:
  521. it caches a list of which :setting:`INSTALLED_APPS` packages have a
  522. ``templates`` subdirectory.
  523. This loader is enabled by default.
  524. ``django.template.loaders.eggs.Loader``
  525. .. class:: eggs.Loader
  526. Just like ``app_directories`` above, but it loads templates from Python
  527. eggs rather than from the filesystem.
  528. This loader is disabled by default.
  529. ``django.template.loaders.cached.Loader``
  530. .. class:: cached.Loader
  531. By default, the templating system will read and compile your templates every
  532. time they need to be rendered. While the Django templating system is quite
  533. fast, the overhead from reading and compiling templates can add up.
  534. The cached template loader is a class-based loader that you configure with
  535. a list of other loaders that it should wrap. The wrapped loaders are used to
  536. locate unknown templates when they are first encountered. The cached loader
  537. then stores the compiled ``Template`` in memory. The cached ``Template``
  538. instance is returned for subsequent requests to load the same template.
  539. For example, to enable template caching with the ``filesystem`` and
  540. ``app_directories`` template loaders you might use the following settings::
  541. TEMPLATE_LOADERS = (
  542. ('django.template.loaders.cached.Loader', (
  543. 'django.template.loaders.filesystem.Loader',
  544. 'django.template.loaders.app_directories.Loader',
  545. )),
  546. )
  547. .. note::
  548. All of the built-in Django template tags are safe to use with the
  549. cached loader, but if you're using custom template tags that come from
  550. third party packages, or that you wrote yourself, you should ensure
  551. that the ``Node`` implementation for each tag is thread-safe. For more
  552. information, see :ref:`template tag thread safety
  553. considerations<template_tag_thread_safety>`.
  554. This loader is disabled by default.
  555. Django uses the template loaders in order according to the
  556. :setting:`TEMPLATE_LOADERS` setting. It uses each loader until a loader finds a
  557. match.
  558. The ``render_to_string`` shortcut
  559. ===================================
  560. .. function:: django.template.loader.render_to_string(template_name, dictionary=None, context_instance=None)
  561. To cut down on the repetitive nature of loading and rendering
  562. templates, Django provides a shortcut function which largely
  563. automates the process: ``render_to_string()`` in
  564. :mod:`django.template.loader`, which loads a template, renders it and
  565. returns the resulting string::
  566. from django.template.loader import render_to_string
  567. rendered = render_to_string('my_template.html', {'foo': 'bar'})
  568. The ``render_to_string`` shortcut takes one required argument --
  569. ``template_name``, which should be the name of the template to load
  570. and render (or a list of template names, in which case Django will use
  571. the first template in the list that exists) -- and two optional arguments:
  572. dictionary
  573. A dictionary to be used as variables and values for the
  574. template's context. This can also be passed as the second
  575. positional argument.
  576. context_instance
  577. An instance of ``Context`` or a subclass (e.g., an instance of
  578. ``RequestContext``) to use as the template's context. This can
  579. also be passed as the third positional argument.
  580. See also the :func:`~django.shortcuts.render_to_response()` shortcut, which
  581. calls ``render_to_string`` and feeds the result into an :class:`~django.http.HttpResponse`
  582. suitable for returning directly from a view.
  583. Configuring the template system in standalone mode
  584. ==================================================
  585. .. note::
  586. This section is only of interest to people trying to use the template
  587. system as an output component in another application. If you're using the
  588. template system as part of a Django application, nothing here applies to
  589. you.
  590. Normally, Django will load all the configuration information it needs from its
  591. own default configuration file, combined with the settings in the module given
  592. in the :envvar:`DJANGO_SETTINGS_MODULE` environment variable. But if you're
  593. using the template system independently of the rest of Django, the environment
  594. variable approach isn't very convenient, because you probably want to configure
  595. the template system in line with the rest of your application rather than
  596. dealing with settings files and pointing to them via environment variables.
  597. To solve this problem, you need to use the manual configuration option described
  598. in :ref:`settings-without-django-settings-module`. Simply import the appropriate
  599. pieces of the templating system and then, *before* you call any of the
  600. templating functions, call :func:`django.conf.settings.configure()` with any
  601. settings you wish to specify. You might want to consider setting at least
  602. :setting:`TEMPLATE_DIRS` (if you're going to use template loaders),
  603. :setting:`DEFAULT_CHARSET` (although the default of ``utf-8`` is probably fine)
  604. and :setting:`TEMPLATE_DEBUG`. If you plan to use the :ttag:`url` template tag,
  605. you will also need to set the :setting:`ROOT_URLCONF` setting. All available
  606. settings are described in the :doc:`settings documentation </ref/settings>`,
  607. and any setting starting with ``TEMPLATE_`` is of obvious interest.
  608. .. _topic-template-alternate-language:
  609. Using an alternative template language
  610. ======================================
  611. The Django ``Template`` and ``Loader`` classes implement a simple API for
  612. loading and rendering templates. By providing some simple wrapper classes that
  613. implement this API we can use third party template systems like `Jinja2
  614. <http://jinja.pocoo.org/docs/>`_ or `Cheetah <http://www.cheetahtemplate.org/>`_. This
  615. allows us to use third-party template libraries without giving up useful Django
  616. features like the Django ``Context`` object and handy shortcuts like
  617. :func:`~django.shortcuts.render_to_response()`.
  618. The core component of the Django templating system is the ``Template`` class.
  619. This class has a very simple interface: it has a constructor that takes a single
  620. positional argument specifying the template string, and a ``render()`` method
  621. that takes a :class:`~django.template.Context` object and returns a string
  622. containing the rendered response.
  623. Suppose we're using a template language that defines a ``Template`` object with
  624. a ``render()`` method that takes a dictionary rather than a ``Context`` object.
  625. We can write a simple wrapper that implements the Django ``Template`` interface::
  626. import some_template_language
  627. class Template(some_template_language.Template):
  628. def render(self, context):
  629. # flatten the Django Context into a single dictionary.
  630. context_dict = {}
  631. for d in context.dicts:
  632. context_dict.update(d)
  633. return super(Template, self).render(context_dict)
  634. That's all that's required to make our fictional ``Template`` class compatible
  635. with the Django loading and rendering system!
  636. The next step is to write a ``Loader`` class that returns instances of our custom
  637. template class instead of the default :class:`~django.template.Template`. Custom ``Loader``
  638. classes should inherit from ``django.template.loader.BaseLoader`` and override
  639. the ``load_template_source()`` method, which takes a ``template_name`` argument,
  640. loads the template from disk (or elsewhere), and returns a tuple:
  641. ``(template_string, template_origin)``.
  642. The ``load_template()`` method of the ``Loader`` class retrieves the template
  643. string by calling ``load_template_source()``, instantiates a ``Template`` from
  644. the template source, and returns a tuple: ``(template, template_origin)``. Since
  645. this is the method that actually instantiates the ``Template``, we'll need to
  646. override it to use our custom template class instead. We can inherit from the
  647. builtin :class:`django.template.loaders.app_directories.Loader` to take advantage
  648. of the ``load_template_source()`` method implemented there::
  649. from django.template.loaders import app_directories
  650. class Loader(app_directories.Loader):
  651. is_usable = True
  652. def load_template(self, template_name, template_dirs=None):
  653. source, origin = self.load_template_source(template_name, template_dirs)
  654. template = Template(source)
  655. return template, origin
  656. Finally, we need to modify our project settings, telling Django to use our custom
  657. loader. Now we can write all of our templates in our alternative template
  658. language while continuing to use the rest of the Django templating system.