api.txt 33 KB

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