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