api.txt 32 KB

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