PageRenderTime 996ms CodeModel.GetById 26ms RepoModel.GetById 52ms app.codeStats 1ms

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