api.txt 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. .. _ref-templates-api:
  2. ====================================================
  3. The Django template language: For Python programmers
  4. ====================================================
  5. This document explains the Django template system from a technical
  6. perspective -- how it works and how to extend it. If you're just looking for
  7. reference on the language syntax, see :ref:`topics-templates`.
  8. If you're looking to use the Django template system as part of another
  9. application -- i.e., without the rest of the framework -- make sure to read
  10. the `configuration`_ section later in this document.
  11. .. _configuration: `configuring the template system in standalone mode`_
  12. Basics
  13. ======
  14. A **template** is a text document, or a normal Python string, that is marked-up
  15. using the Django template language. A template can contain **block tags** or
  16. **variables**.
  17. A **block tag** is a symbol within a template that does something.
  18. This definition is deliberately vague. For example, a block tag can output
  19. content, serve as a control structure (an "if" statement or "for" loop), grab
  20. content from a database or enable access to other template tags.
  21. Block tags are surrounded by ``"{%"`` and ``"%}"``.
  22. Example template with block tags:
  23. .. code-block:: html+django
  24. {% if is_logged_in %}Thanks for logging in!{% else %}Please log in.{% endif %}
  25. A **variable** is a symbol within a template that outputs a value.
  26. Variable tags are surrounded by ``"{{"`` and ``"}}"``.
  27. Example template with variables:
  28. .. code-block:: html+django
  29. My first name is {{ first_name }}. My last name is {{ last_name }}.
  30. A **context** is a "variable name" -> "variable value" mapping that is passed
  31. to a template.
  32. A template **renders** a context by replacing the variable "holes" with values
  33. from the context and executing all block tags.
  34. Using the template system
  35. =========================
  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 ``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. Once you have a compiled ``Template`` object, you can render a context -- or
  58. multiple contexts -- with it. The ``Context`` class lives at
  59. ``django.template.Context``, and the constructor takes two (optional)
  60. arguments:
  61. * A dictionary mapping variable names to variable values.
  62. * The name of the current application. This application name is used
  63. to help :ref:`resolve namespaced URLs<topics-http-reversing-url-namespaces>`.
  64. If you're not using namespaced URLs, you can ignore this argument.
  65. Call the ``Template`` object's ``render()`` method with the context to "fill" the
  66. template::
  67. >>> from django.template import Context, Template
  68. >>> t = Template("My name is {{ my_name }}.")
  69. >>> c = Context({"my_name": "Adrian"})
  70. >>> t.render(c)
  71. "My name is Adrian."
  72. >>> c = Context({"my_name": "Dolores"})
  73. >>> t.render(c)
  74. "My name is Dolores."
  75. Variable names must consist of any letter (A-Z), any digit (0-9), an underscore
  76. or a dot.
  77. Dots have a special meaning in template rendering. A dot in a variable name
  78. signifies **lookup**. Specifically, when the template system encounters a dot
  79. in a variable name, it tries the following lookups, in this order:
  80. * Dictionary lookup. Example: ``foo["bar"]``
  81. * Attribute lookup. Example: ``foo.bar``
  82. * Method call. 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.
  86. Here are a few examples::
  87. >>> from django.template import Context, Template
  88. >>> t = Template("My name is {{ person.first_name }}.")
  89. >>> d = {"person": {"first_name": "Joe", "last_name": "Johnson"}}
  90. >>> t.render(Context(d))
  91. "My name is Joe."
  92. >>> class PersonClass: pass
  93. >>> p = PersonClass()
  94. >>> p.first_name = "Ron"
  95. >>> p.last_name = "Nasty"
  96. >>> t.render(Context({"person": p}))
  97. "My name is Ron."
  98. >>> class PersonClass2:
  99. ... def first_name(self):
  100. ... return "Samantha"
  101. >>> p = PersonClass2()
  102. >>> t.render(Context({"person": p}))
  103. "My name is Samantha."
  104. >>> t = Template("The first stooge in the list is {{ stooges.0 }}.")
  105. >>> c = Context({"stooges": ["Larry", "Curly", "Moe"]})
  106. >>> t.render(c)
  107. "The first stooge in the list is Larry."
  108. Method lookups are slightly more complex than the other lookup types. Here are
  109. some things to keep in mind:
  110. * If, during the method lookup, a method raises an exception, the exception
  111. will be propagated, unless the exception has an attribute
  112. ``silent_variable_failure`` whose value is ``True``. If the exception
  113. *does* have a ``silent_variable_failure`` attribute, the variable will
  114. render as an empty string. Example::
  115. >>> t = Template("My name is {{ person.first_name }}.")
  116. >>> class PersonClass3:
  117. ... def first_name(self):
  118. ... raise AssertionError, "foo"
  119. >>> p = PersonClass3()
  120. >>> t.render(Context({"person": p}))
  121. Traceback (most recent call last):
  122. ...
  123. AssertionError: foo
  124. >>> class SilentAssertionError(Exception):
  125. ... silent_variable_failure = True
  126. >>> class PersonClass4:
  127. ... def first_name(self):
  128. ... raise SilentAssertionError
  129. >>> p = PersonClass4()
  130. >>> t.render(Context({"person": p}))
  131. "My name is ."
  132. Note that ``django.core.exceptions.ObjectDoesNotExist``, which is the
  133. base class for all Django database API ``DoesNotExist`` exceptions, has
  134. ``silent_variable_failure = True``. So if you're using Django templates
  135. with Django model objects, any ``DoesNotExist`` exception will fail
  136. silently.
  137. * A method call will only work if the method has no required arguments.
  138. Otherwise, the system will move to the next lookup type (list-index
  139. lookup).
  140. * Obviously, some methods have side effects, and it'd be either foolish or
  141. a security hole to allow the template system to access them.
  142. A good example is the ``delete()`` method on each Django model object.
  143. The template system shouldn't be allowed to do something like this::
  144. I will now delete this valuable data. {{ data.delete }}
  145. To prevent this, set a function attribute ``alters_data`` on the method.
  146. The template system won't execute a method if the method has
  147. ``alters_data=True`` set. The dynamically-generated ``delete()`` and
  148. ``save()`` methods on Django model objects get ``alters_data=True``
  149. automatically. Example::
  150. def sensitive_function(self):
  151. self.database_record.delete()
  152. sensitive_function.alters_data = True
  153. .. _invalid-template-variables:
  154. How invalid variables are handled
  155. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  156. Generally, if a variable doesn't exist, the template system inserts the
  157. value of the :setting:`TEMPLATE_STRING_IF_INVALID` setting, which is set to
  158. ``''`` (the empty string) by default.
  159. Filters that are applied to an invalid variable will only be applied if
  160. :setting:`TEMPLATE_STRING_IF_INVALID` is set to ``''`` (the empty string). If
  161. :setting:`TEMPLATE_STRING_IF_INVALID` is set to any other value, variable
  162. filters will be ignored.
  163. This behavior is slightly different for the ``if``, ``for`` and ``regroup``
  164. template tags. If an invalid variable is provided to one of these template
  165. tags, the variable will be interpreted as ``None``. Filters are always
  166. applied to invalid variables within these template tags.
  167. If :setting:`TEMPLATE_STRING_IF_INVALID` contains a ``'%s'``, the format marker will
  168. be replaced with the name of the invalid variable.
  169. .. admonition:: For debug purposes only!
  170. While :setting:`TEMPLATE_STRING_IF_INVALID` can be a useful debugging tool,
  171. it is a bad idea to turn it on as a 'development default'.
  172. Many templates, including those in the Admin site, rely upon the
  173. silence of the template system when a non-existent variable is
  174. encountered. If you assign a value other than ``''`` to
  175. :setting:`TEMPLATE_STRING_IF_INVALID`, you will experience rendering
  176. problems with these templates and sites.
  177. Generally, :setting:`TEMPLATE_STRING_IF_INVALID` should only be enabled
  178. in order to debug a specific template problem, then cleared
  179. once debugging is complete.
  180. Playing with Context objects
  181. ----------------------------
  182. Most of the time, you'll instantiate ``Context`` objects by passing in a
  183. fully-populated dictionary to ``Context()``. But you can add and delete items
  184. from a ``Context`` object once it's been instantiated, too, using standard
  185. dictionary syntax::
  186. >>> c = Context({"foo": "bar"})
  187. >>> c['foo']
  188. 'bar'
  189. >>> del c['foo']
  190. >>> c['foo']
  191. ''
  192. >>> c['newvariable'] = 'hello'
  193. >>> c['newvariable']
  194. 'hello'
  195. A ``Context`` object is a stack. That is, you can ``push()`` and ``pop()`` it.
  196. If you ``pop()`` too much, it'll raise
  197. ``django.template.ContextPopException``::
  198. >>> c = Context()
  199. >>> c['foo'] = 'first level'
  200. >>> c.push()
  201. >>> c['foo'] = 'second level'
  202. >>> c['foo']
  203. 'second level'
  204. >>> c.pop()
  205. >>> c['foo']
  206. 'first level'
  207. >>> c['foo'] = 'overwritten'
  208. >>> c['foo']
  209. 'overwritten'
  210. >>> c.pop()
  211. Traceback (most recent call last):
  212. ...
  213. django.template.ContextPopException
  214. Using a ``Context`` as a stack comes in handy in some custom template tags, as
  215. you'll see below.
  216. .. _subclassing-context-requestcontext:
  217. Subclassing Context: RequestContext
  218. -----------------------------------
  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.core.context_processors.auth",
  233. "django.core.context_processors.debug",
  234. "django.core.context_processors.i18n",
  235. "django.core.context_processors.media",
  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 :ref:`messages documentation <ref-contrib-messages>`.
  246. Each processor is applied in order. That means, if one processor adds a
  247. variable to the context and a second processor adds a variable with the same
  248. name, the second will override the first. The default processors are explained
  249. below.
  250. Also, you can give ``RequestContext`` a list of additional processors, using the
  251. optional, third positional argument, ``processors``. In this example, the
  252. ``RequestContext`` instance gets a ``ip_address`` variable::
  253. def ip_address_processor(request):
  254. return {'ip_address': request.META['REMOTE_ADDR']}
  255. def some_view(request):
  256. # ...
  257. c = RequestContext(request, {
  258. 'foo': 'bar',
  259. }, [ip_address_processor])
  260. return HttpResponse(t.render(c))
  261. .. note::
  262. If you're using Django's ``render_to_response()`` shortcut to populate a
  263. template with the contents of a dictionary, your template will be passed a
  264. ``Context`` instance by default (not a ``RequestContext``). To use a
  265. ``RequestContext`` in your template rendering, pass an optional third
  266. argument to ``render_to_response()``: a ``RequestContext``
  267. instance. Your code might look like this::
  268. def some_view(request):
  269. # ...
  270. return render_to_response('my_template.html',
  271. my_data_dictionary,
  272. context_instance=RequestContext(request))
  273. Here's what each of the default processors does:
  274. django.core.context_processors.auth
  275. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  276. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  277. ``RequestContext`` will contain these three variables:
  278. * ``user`` -- An ``auth.User`` instance representing the currently
  279. logged-in user (or an ``AnonymousUser`` instance, if the client isn't
  280. logged in).
  281. * ``messages`` -- A list of messages (as strings) that have been set
  282. via the :ref:`messages framework <ref-contrib-messages>`.
  283. * ``perms`` -- An instance of
  284. ``django.core.context_processors.PermWrapper``, representing the
  285. permissions that the currently logged-in user has.
  286. .. versionchanged:: 1.2
  287. Prior to version 1.2, the ``messages`` variable was a lazy accessor for
  288. ``user.get_and_delete_messages()``. It has been changed to include any
  289. messages added via the :ref:`messages framework <ref-contrib-messages`.
  290. django.core.context_processors.debug
  291. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  292. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  293. ``RequestContext`` will contain these two variables -- but only if your
  294. :setting:`DEBUG` setting is set to ``True`` and the request's IP address
  295. (``request.META['REMOTE_ADDR']``) is in the :setting:`INTERNAL_IPS` setting:
  296. * ``debug`` -- ``True``. You can use this in templates to test whether
  297. you're in :setting:`DEBUG` mode.
  298. * ``sql_queries`` -- A list of ``{'sql': ..., 'time': ...}`` dictionaries,
  299. representing every SQL query that has happened so far during the request
  300. and how long it took. The list is in order by query.
  301. django.core.context_processors.i18n
  302. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  303. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  304. ``RequestContext`` will contain these two variables:
  305. * ``LANGUAGES`` -- The value of the :setting:`LANGUAGES` setting.
  306. * ``LANGUAGE_CODE`` -- ``request.LANGUAGE_CODE``, if it exists. Otherwise,
  307. the value of the :setting:`LANGUAGE_CODE` setting.
  308. See :ref:`topics-i18n` for more.
  309. django.core.context_processors.media
  310. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  311. .. versionadded:: 1.0
  312. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  313. ``RequestContext`` will contain a variable ``MEDIA_URL``, providing the
  314. value of the :setting:`MEDIA_URL` setting.
  315. django.core.context_processors.csrf
  316. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  317. .. versionadded:: 1.2
  318. This processor adds a token that is needed by the ``csrf_token`` template tag
  319. for protection against :ref:`Cross Site Request Forgeries <ref-contrib-csrf>`.
  320. django.core.context_processors.request
  321. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  322. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  323. ``RequestContext`` will contain a variable ``request``, which is the current
  324. :class:`~django.http.HttpRequest`. Note that this processor is not enabled by default;
  325. you'll have to activate it.
  326. django.contrib.messages.context_processors.messages
  327. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  328. If :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains this processor, every
  329. ``RequestContext`` will contain a single additional variable:
  330. * ``messages`` -- A list of messages (as strings) that have been set
  331. via the user model (using ``user.message_set.create``) or through
  332. the :ref:`messages framework <ref-contrib-messages>`.
  333. .. versionadded:: 1.2
  334. This template context variable was previously supplied by the ``'auth'``
  335. context processor. For backwards compatibility the ``'auth'`` context
  336. processor will continue to supply the ``messages`` variable until Django
  337. 1.4. If you use the ``messages`` variable, your project will work with
  338. either (or both) context processors, but it is recommended to add
  339. ``django.contrib.messages.context_processors.messages`` so your project
  340. will be prepared for the future upgrade.
  341. Writing your own context processors
  342. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  343. A context processor has a very simple interface: It's just a Python function
  344. that takes one argument, an ``HttpRequest`` object, and returns a dictionary
  345. that gets added to the template context. Each context processor *must* return
  346. a dictionary.
  347. Custom context processors can live anywhere in your code base. All Django cares
  348. about is that your custom context processors are pointed-to by your
  349. :setting:`TEMPLATE_CONTEXT_PROCESSORS` setting.
  350. Loading templates
  351. -----------------
  352. Generally, you'll store templates in files on your filesystem rather than using
  353. the low-level ``Template`` API yourself. Save templates in a directory
  354. specified as a **template directory**.
  355. Django searches for template directories in a number of places, depending on
  356. your template-loader settings (see "Loader types" below), but the most basic
  357. way of specifying template directories is by using the :setting:`TEMPLATE_DIRS`
  358. setting.
  359. The TEMPLATE_DIRS setting
  360. ~~~~~~~~~~~~~~~~~~~~~~~~~
  361. Tell Django what your template directories are by using the
  362. :setting:`TEMPLATE_DIRS` setting in your settings file. This should be set to a
  363. list or tuple of strings that contain full paths to your template
  364. directory(ies). Example::
  365. TEMPLATE_DIRS = (
  366. "/home/html/templates/lawrence.com",
  367. "/home/html/templates/default",
  368. )
  369. Your templates can go anywhere you want, as long as the directories and
  370. templates are readable by the Web server. They can have any extension you want,
  371. such as ``.html`` or ``.txt``, or they can have no extension at all.
  372. Note that these paths should use Unix-style forward slashes, even on Windows.
  373. .. _ref-templates-api-the-python-api:
  374. The Python API
  375. ~~~~~~~~~~~~~~
  376. Django has two ways to load templates from files:
  377. ``django.template.loader.get_template(template_name)``
  378. ``get_template`` returns the compiled template (a ``Template`` object) for
  379. the template with the given name. If the template doesn't exist, it raises
  380. ``django.template.TemplateDoesNotExist``.
  381. ``django.template.loader.select_template(template_name_list)``
  382. ``select_template`` is just like ``get_template``, except it takes a list
  383. of template names. Of the list, it returns the first template that exists.
  384. For example, if you call ``get_template('story_detail.html')`` and have the
  385. above :setting:`TEMPLATE_DIRS` setting, here are the files Django will look for,
  386. in order:
  387. * ``/home/html/templates/lawrence.com/story_detail.html``
  388. * ``/home/html/templates/default/story_detail.html``
  389. If you call ``select_template(['story_253_detail.html', 'story_detail.html'])``,
  390. here's what Django will look for:
  391. * ``/home/html/templates/lawrence.com/story_253_detail.html``
  392. * ``/home/html/templates/default/story_253_detail.html``
  393. * ``/home/html/templates/lawrence.com/story_detail.html``
  394. * ``/home/html/templates/default/story_detail.html``
  395. When Django finds a template that exists, it stops looking.
  396. .. admonition:: Tip
  397. You can use ``select_template()`` for super-flexible "templatability." For
  398. example, if you've written a news story and want some stories to have
  399. custom templates, use something like
  400. ``select_template(['story_%s_detail.html' % story.id, 'story_detail.html'])``.
  401. That'll allow you to use a custom template for an individual story, with a
  402. fallback template for stories that don't have custom templates.
  403. Using subdirectories
  404. ~~~~~~~~~~~~~~~~~~~~
  405. It's possible -- and preferable -- to organize templates in subdirectories of
  406. the template directory. The convention is to make a subdirectory for each
  407. Django app, with subdirectories within those subdirectories as needed.
  408. Do this for your own sanity. Storing all templates in the root level of a
  409. single directory gets messy.
  410. To load a template that's within a subdirectory, just use a slash, like so::
  411. get_template('news/story_detail.html')
  412. Using the same :setting:`TEMPLATE_DIRS` setting from above, this example
  413. ``get_template()`` call will attempt to load the following templates:
  414. * ``/home/html/templates/lawrence.com/news/story_detail.html``
  415. * ``/home/html/templates/default/news/story_detail.html``
  416. .. _template-loaders:
  417. Loader types
  418. ~~~~~~~~~~~~
  419. By default, Django uses a filesystem-based template loader, but Django comes
  420. with a few other template loaders, which know how to load templates from other
  421. sources.
  422. Some of these other loaders are disabled by default, but you can activate them
  423. by editing your :setting:`TEMPLATE_LOADERS` setting. :setting:`TEMPLATE_LOADERS`
  424. should be a tuple of strings, where each string represents a template loader.
  425. Here are the template loaders that come with Django:
  426. ``django.template.loaders.filesystem.load_template_source``
  427. Loads templates from the filesystem, according to :setting:`TEMPLATE_DIRS`.
  428. This loader is enabled by default.
  429. ``django.template.loaders.app_directories.load_template_source``
  430. Loads templates from Django apps on the filesystem. For each app in
  431. :setting:`INSTALLED_APPS`, the loader looks for a ``templates``
  432. subdirectory. If the directory exists, Django looks for templates in there.
  433. This means you can store templates with your individual apps. This also
  434. makes it easy to distribute Django apps with default templates.
  435. For example, for this setting::
  436. INSTALLED_APPS = ('myproject.polls', 'myproject.music')
  437. ...then ``get_template('foo.html')`` will look for templates in these
  438. directories, in this order:
  439. * ``/path/to/myproject/polls/templates/foo.html``
  440. * ``/path/to/myproject/music/templates/foo.html``
  441. Note that the loader performs an optimization when it is first imported: It
  442. caches a list of which :setting:`INSTALLED_APPS` packages have a
  443. ``templates`` subdirectory.
  444. This loader is enabled by default.
  445. ``django.template.loaders.eggs.load_template_source``
  446. Just like ``app_directories`` above, but it loads templates from Python
  447. eggs rather than from the filesystem.
  448. This loader is disabled by default.
  449. Django uses the template loaders in order according to the
  450. :setting:`TEMPLATE_LOADERS` setting. It uses each loader until a loader finds a
  451. match.
  452. The ``render_to_string()`` shortcut
  453. ===================================
  454. To cut down on the repetitive nature of loading and rendering
  455. templates, Django provides a shortcut function which largely
  456. automates the process: ``render_to_string()`` in
  457. ``django.template.loader``, which loads a template, renders it and
  458. returns the resulting string::
  459. from django.template.loader import render_to_string
  460. rendered = render_to_string('my_template.html', { 'foo': 'bar' })
  461. The ``render_to_string`` shortcut takes one required argument --
  462. ``template_name``, which should be the name of the template to load
  463. and render -- and two optional arguments:
  464. dictionary
  465. A dictionary to be used as variables and values for the
  466. template's context. This can also be passed as the second
  467. positional argument.
  468. context_instance
  469. An instance of ``Context`` or a subclass (e.g., an instance of
  470. ``RequestContext``) to use as the template's context. This can
  471. also be passed as the third positional argument.
  472. See also the :func:`~django.shortcuts.render_to_response()` shortcut, which
  473. calls ``render_to_string`` and feeds the result into an ``HttpResponse``
  474. suitable for returning directly from a view.
  475. Configuring the template system in standalone mode
  476. ==================================================
  477. .. note::
  478. This section is only of interest to people trying to use the template
  479. system as an output component in another application. If you're using the
  480. template system as part of a Django application, nothing here applies to
  481. you.
  482. Normally, Django will load all the configuration information it needs from its
  483. own default configuration file, combined with the settings in the module given
  484. in the :setting:`DJANGO_SETTINGS_MODULE` environment variable. But if you're
  485. using the template system independently of the rest of Django, the environment
  486. variable approach isn't very convenient, because you probably want to configure
  487. the template system in line with the rest of your application rather than
  488. dealing with settings files and pointing to them via environment variables.
  489. To solve this problem, you need to use the manual configuration option described
  490. in :ref:`settings-without-django-settings-module`. Simply import the appropriate
  491. pieces of the templating system and then, *before* you call any of the
  492. templating functions, call ``django.conf.settings.configure()`` with any
  493. settings you wish to specify. You might want to consider setting at least
  494. :setting:`TEMPLATE_DIRS` (if you're going to use template loaders),
  495. :setting:`DEFAULT_CHARSET` (although the default of ``utf-8`` is probably fine)
  496. and :setting:`TEMPLATE_DEBUG`. All available settings are described in the
  497. :ref:`settings documentation <ref-settings>`, and any setting starting with
  498. ``TEMPLATE_`` is of obvious interest.