api.txt 34 KB

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