The Django template language: for Python programmers

This document explains the Django template system from a technicalperspective — how it works and how to extend it. If you're just looking forreference on the language syntax, see The Django template language.

It assumes an understanding of templates, contexts, variables, tags, andrendering. Start with the introduction to the Django template language if you aren't familiar with these concepts.

Overview

Using the template system in Python is a three-step process:

Configuring an engine

If you are simply using theDjangoTemplates backend, thisprobably isn't the documentation you're looking for. An instance of theEngine class described below is accessible using the engine attributeof that backend and any attribute defaults mentioned below are overridden bywhat's passed by DjangoTemplates.

  • class Engine(dirs=None, app_dirs=False, context_processors=None, debug=False, loaders=None, string_if_invalid='', file_charset='utf-8', libraries=None, builtins=None, autoescape=True)[源代码]
  • When instantiating an Engine all arguments must be passed as keywordarguments:

    • dirs is a list of directories where the engine should look fortemplate source files. It is used to configurefilesystem.Loader.

It defaults to an empty list.

  • app_dirs only affects the default value of loaders. See below.

It defaults to False.

  • autoescape controls whether HTML autoescaping is enabled.

It defaults to True.

警告

Only set it to False if you're rendering non-HTML templates!

  • context_processors is a list of dotted Python paths to callablesthat are used to populate the context when a template is rendered with arequest. These callables take a request object as their argument andreturn a dict of items to be merged into the context.

It defaults to an empty list.

See RequestContext for more information.

  • debug is a boolean that turns on/off template debug mode. If it isTrue, the template engine will store additional debug informationwhich can be used to display a detailed report for any exception raisedduring template rendering.

It defaults to False.

  • loaders is a list of template loader classes, specified as strings.Each Loader class knows how to import templates from a particularsource. Optionally, a tuple can be used instead of a string. The firstitem in the tuple should be the Loader class name, subsequent itemsare passed to the Loader during initialization.

It defaults to a list containing:

  1. - <code>&#39;django.template.loaders.filesystem.Loader&#39;</code>
  2. - <code>&#39;django.template.loaders.app_directories.Loader&#39;</code> if and only if<code>app_dirs</code> is <code>True</code>.

If debug is False, these loaders are wrapped indjango.template.loaders.cached.Loader.

See Loader types for details.

  • string_if_invalid is the output, as a string, that the templatesystem should use for invalid (e.g. misspelled) variables.

It defaults to the empty string.

See How invalid variables are handled for details.

  • file_charset is the charset used to read template files on disk.

It defaults to 'utf-8'.

  • 'libraries': A dictionary of labels and dotted Python paths of templatetag modules to register with the template engine. This is used to add newlibraries or provide alternate labels for existing ones. For example:
  1. Engine(
  2. libraries={
  3. 'myapp_tags': 'path.to.myapp.tags',
  4. 'admin.urls': 'django.contrib.admin.templatetags.admin_urls',
  5. },
  6. )

Libraries can be loaded by passing the corresponding dictionary key tothe {% load %} tag.

  • 'builtins': A list of dotted Python paths of template tag modules toadd to built-ins. For example:
  1. Engine(
  2. builtins=['myapp.builtins'],
  3. )

Tags and filters from built-in libraries can be used without first callingthe {% load %} tag.

It's required for preserving APIs that rely on a globally available,implicitly configured engine. Any other use is strongly discouraged.

  • Engine.fromstring(_template_code)[源代码]
  • Compiles the given template code and returns a Template object.

  • Engine.gettemplate(_template_name)[源代码]

  • Loads a template with the given name, compiles it and returns aTemplate object.

  • Engine.selecttemplate(_template_name_list)[源代码]

  • Like get_template(), except it takes a list of namesand returns the first template that was found.

Loading a template

The recommended way to create a Template is by calling the factorymethods of the Engine: get_template(),select_template() and from_string().

In a Django project where the TEMPLATES setting defines aDjangoTemplates engine, it'spossible to instantiate a Template directly. If more than oneDjangoTemplates engine is defined,the first one will be used.

  • class Template[源代码]
  • This class lives at django.template.Template. The constructor takesone argument — the raw template code:
  1. from django.template import Template
  2.  
  3. template = Template("My name is {{ my_name }}.")

Behind the scenes

The system only parses your raw template code once — when you create theTemplate object. From then on, it's stored internally as a treestructure for performance.

Even the parsing itself is quite fast. Most of the parsing happens via asingle call to a single, short, regular expression.

Rendering a context

Once you have a compiled Template object, you can render a contextwith it. You can reuse the same template to render it several times withdifferent contexts.

  • class Context(dict=None_)[源代码]
  • The constructor of django.template.Context takes an optional argument —a dictionary mapping variable names to variable values.

For details, see Playing with Context objects below.

  1. >>> from django.template import Context, Template
  2. >>> template = Template("My name is {{ my_name }}.")
  3.  
  4. >>> context = Context({"my_name": "Adrian"})
  5. >>> template.render(context)
  6. "My name is Adrian."
  7.  
  8. >>> context = Context({"my_name": "Dolores"})
  9. >>> template.render(context)
  10. "My name is Dolores."

Variables and lookups

Variable names must consist of any letter (A-Z), any digit (0-9), an underscore(but they must not start with an underscore) or a dot.

Dots have a special meaning in template rendering. A dot in a variable namesignifies a lookup. Specifically, when the template system encounters adot in a variable name, it tries the following lookups, in this order:

  • Dictionary lookup. Example: foo["bar"]
  • Attribute lookup. Example: foo.bar
  • List-index lookup. Example: foo[bar]
    Note that "bar" in a template expression like {{ foo.bar }} will beinterpreted as a literal string and not using the value of the variable "bar",if one exists in the template context.

The template system uses the first lookup type that works. It's short-circuitlogic. Here are a few examples:

  1. >>> from django.template import Context, Template
  2. >>> t = Template("My name is {{ person.first_name }}.")
  3. >>> d = {"person": {"first_name": "Joe", "last_name": "Johnson"}}
  4. >>> t.render(Context(d))
  5. "My name is Joe."
  6.  
  7. >>> class PersonClass: pass
  8. >>> p = PersonClass()
  9. >>> p.first_name = "Ron"
  10. >>> p.last_name = "Nasty"
  11. >>> t.render(Context({"person": p}))
  12. "My name is Ron."
  13.  
  14. >>> t = Template("The first stooge in the list is {{ stooges.0 }}.")
  15. >>> c = Context({"stooges": ["Larry", "Curly", "Moe"]})
  16. >>> t.render(c)
  17. "The first stooge in the list is Larry."

If any part of the variable is callable, the template system will try callingit. Example:

  1. >>> class PersonClass2:
  2. ... def name(self):
  3. ... return "Samantha"
  4. >>> t = Template("My name is {{ person.name }}.")
  5. >>> t.render(Context({"person": PersonClass2}))
  6. "My name is Samantha."

Callable variables are slightly more complex than variables which only requirestraight lookups. Here are some things to keep in mind:

  • If the variable raises an exception when called, the exception will bepropagated, unless the exception has an attributesilentvariable_failure whose value is True. If the exception_does have a silent_variable_failure attribute whose value isTrue, the variable will render as the value of the engine'sstring_if_invalid configuration option (an empty string, by default).Example:
  1. >>> t = Template("My name is {{ person.first_name }}.")
  2. >>> class PersonClass3:
  3. ... def first_name(self):
  4. ... raise AssertionError("foo")
  5. >>> p = PersonClass3()
  6. >>> t.render(Context({"person": p}))
  7. Traceback (most recent call last):
  8. ...
  9. AssertionError: foo
  10.  
  11. >>> class SilentAssertionError(Exception):
  12. ... silent_variable_failure = True
  13. >>> class PersonClass4:
  14. ... def first_name(self):
  15. ... raise SilentAssertionError
  16. >>> p = PersonClass4()
  17. >>> t.render(Context({"person": p}))
  18. "My name is ."

Note that django.core.exceptions.ObjectDoesNotExist, which is thebase class for all Django database API DoesNotExist exceptions, hassilent_variable_failure = True. So if you're using Django templateswith Django model objects, any DoesNotExist exception will failsilently.

  • A variable can only be called if it has no required arguments. Otherwise,the system will return the value of the engine's string_if_invalidoption.

  • Obviously, there can be side effects when calling some variables, andit'd be either foolish or a security hole to allow the template systemto access them.

A good example is the delete() method oneach Django model object. The template system shouldn't be allowed to dosomething like this:

  1. I will now delete this valuable data. {{ data.delete }}

To prevent this, set an alters_data attribute on the callablevariable. The template system won't call a variable if it hasalters_data=True set, and will instead replace the variable withstring_if_invalid, unconditionally. Thedynamically-generated delete() andsave() methods on Django model objects getalters_data=True automatically. Example:

  1. def sensitive_function(self):
  2. self.database_record.delete()
  3. sensitive_function.alters_data = True
  • Occasionally you may want to turn off this feature for other reasons,and tell the template system to leave a variable uncalled no matterwhat. To do so, set a do_not_call_in_templates attribute on thecallable with the value True. The template system then will act asif your variable is not callable (allowing you to access attributes ofthe callable, for example).

How invalid variables are handled

Generally, if a variable doesn't exist, the template system inserts the valueof the engine's string_if_invalid configuration option, which is set to'' (the empty string) by default.

Filters that are applied to an invalid variable will only be applied ifstring_if_invalid is set to '' (the empty string). Ifstring_if_invalid is set to any other value, variable filters will beignored.

This behavior is slightly different for the if, for and regrouptemplate tags. If an invalid variable is provided to one of these templatetags, the variable will be interpreted as None. Filters are alwaysapplied to invalid variables within these template tags.

If string_if_invalid contains a '%s', the format marker will bereplaced with the name of the invalid variable.

For debug purposes only!

While string_if_invalid can be a useful debugging tool, it is a badidea to turn it on as a 'development default'.

Many templates, including some of Django's, rely upon the silence of thetemplate system when a nonexistent variable is encountered. If you assign avalue other than '' to string_if_invalid, you will experiencerendering problems with these templates and sites.

Generally, string_if_invalid should only be enabled in order to debuga specific template problem, then cleared once debugging is complete.

Built-in variables

Every context contains True, False and None. As you would expect,these variables resolve to the corresponding Python objects.

Limitations with string literals

Django's template language has no way to escape the characters used for its ownsyntax. For example, the templatetag tag is required if you need tooutput character sequences like {% and %}.

A similar issue exists if you want to include these sequences in template filteror tag arguments. For example, when parsing a block tag, Django's templateparser looks for the first occurrence of %} after a {%. This preventsthe use of "%}" as a string literal. For example, a TemplateSyntaxErrorwill be raised for the following expressions:

  1. {% include "template.html" tvar="Some string literal with %} in it." %}
  2.  
  3. {% with tvar="Some string literal with %} in it." %}{% endwith %}

The same issue can be triggered by using a reserved sequence in filterarguments:

  1. {{ some.variable|default:"}}" }}

If you need to use strings with these sequences, store them in templatevariables or use a custom template tag or filter to workaround the limitation.

Playing with Context objects

Most of the time, you'll instantiate Context objects by passing in afully-populated dictionary to Context(). But you can add and delete itemsfrom a Context object once it's been instantiated, too, using standarddictionary syntax:

  1. >>> from django.template import Context
  2. >>> c = Context({"foo": "bar"})
  3. >>> c['foo']
  4. 'bar'
  5. >>> del c['foo']
  6. >>> c['foo']
  7. Traceback (most recent call last):
  8. ...
  9. KeyError: 'foo'
  10. >>> c['newvariable'] = 'hello'
  11. >>> c['newvariable']
  12. 'hello'
  • Context.get(key, otherwise=None)
  • Returns the value for key if key is in the context, else returnsotherwise.

  • Context.setdefault(key, default=None)

  • If key is in the context, returns its value. Otherwise inserts keywith a value of default and returns default.

  • Context.pop()

  • Context.push()
  • exception ContextPopException[源代码]
  • A Context object is a stack. That is, you can push() and pop() it.If you pop() too much, it'll raisedjango.template.ContextPopException:
  1. >>> c = Context()
  2. >>> c['foo'] = 'first level'
  3. >>> c.push()
  4. {}
  5. >>> c['foo'] = 'second level'
  6. >>> c['foo']
  7. 'second level'
  8. >>> c.pop()
  9. {'foo': 'second level'}
  10. >>> c['foo']
  11. 'first level'
  12. >>> c['foo'] = 'overwritten'
  13. >>> c['foo']
  14. 'overwritten'
  15. >>> c.pop()
  16. Traceback (most recent call last):
  17. ...
  18. ContextPopException

You can also use push() as a context manager to ensure a matching pop()is called.

  1. >>> c = Context()
  2. >>> c['foo'] = 'first level'
  3. >>> with c.push():
  4. ... c['foo'] = 'second level'
  5. ... c['foo']
  6. 'second level'
  7. >>> c['foo']
  8. 'first level'

All arguments passed to push() will be passed to the dict constructorused to build the new context level.

  1. >>> c = Context()
  2. >>> c['foo'] = 'first level'
  3. >>> with c.push(foo='second level'):
  4. ... c['foo']
  5. 'second level'
  6. >>> c['foo']
  7. 'first level'
  • Context.update(other_dict)[源代码]
  • In addition to push() and pop(), the Contextobject also defines an update() method. This works like push()but takes a dictionary as an argument and pushes that dictionary ontothe stack instead of an empty one.
  1. >>> c = Context()
  2. >>> c['foo'] = 'first level'
  3. >>> c.update({'foo': 'updated'})
  4. {'foo': 'updated'}
  5. >>> c['foo']
  6. 'updated'
  7. >>> c.pop()
  8. {'foo': 'updated'}
  9. >>> c['foo']
  10. 'first level'

Like push(), you can use update() as a context manager to ensure amatching pop() is called.

  1. >>> c = Context()
  2. >>> c['foo'] = 'first level'
  3. >>> with c.update({'foo': 'second level'}):
  4. ... c['foo']
  5. 'second level'
  6. >>> c['foo']
  7. 'first level'

Using a Context as a stack comes in handy in some custom templatetags.

  • Context.flatten()
  • Using flatten() method you can get whole Context stack as one dictionaryincluding builtin variables.
  1. >>> c = Context()
  2. >>> c['foo'] = 'first level'
  3. >>> c.update({'bar': 'second level'})
  4. {'bar': 'second level'}
  5. >>> c.flatten()
  6. {'True': True, 'None': None, 'foo': 'first level', 'False': False, 'bar': 'second level'}

A flatten() method is also internally used to make Context objects comparable.

  1. >>> c1 = Context()
  2. >>> c1['foo'] = 'first level'
  3. >>> c1['bar'] = 'second level'
  4. >>> c2 = Context()
  5. >>> c2.update({'bar': 'second level', 'foo': 'first level'})
  6. {'foo': 'first level', 'bar': 'second level'}
  7. >>> c1 == c2
  8. True

Result from flatten() can be useful in unit tests to compare Contextagainst dict:

  1. class ContextTest(unittest.TestCase):
  2. def test_against_dictionary(self):
  3. c1 = Context()
  4. c1['update'] = 'value'
  5. self.assertEqual(c1.flatten(), {
  6. 'True': True,
  7. 'None': None,
  8. 'False': False,
  9. 'update': 'value',
  10. })

Using RequestContext

  • class RequestContext(request, dict=None, _processors=None)[源代码]
  • Django comes with a special Context class,django.template.RequestContext, that acts slightly differently from thenormal django.template.Context. The first difference is that it takes anHttpRequest as its first argument. For example:
  1. c = RequestContext(request, {
  2. 'foo': 'bar',
  3. })

The second difference is that it automatically populates the context with afew variables, according to the engine's context_processors configurationoption.

The context_processors option is a list of callables — called contextprocessors — that take a request object as their argument and return adictionary of items to be merged into the context. In the default generatedsettings file, the default template engine contains the following contextprocessors:

  1. [
  2. 'django.template.context_processors.debug',
  3. 'django.template.context_processors.request',
  4. 'django.contrib.auth.context_processors.auth',
  5. 'django.contrib.messages.context_processors.messages',
  6. ]

In addition to these, RequestContext always enables'django.template.context_processors.csrf'. This is a security relatedcontext processor required by the admin and other contrib apps, and, in caseof accidental misconfiguration, it is deliberately hardcoded in and cannot beturned off in the context_processors option.

Each processor is applied in order. That means, if one processor adds avariable to the context and a second processor adds a variable with the samename, the second will override the first. The default processors are explainedbelow.

When context processors are applied

Context processors are applied on top of context data. This means that acontext processor may overwrite variables you've supplied to yourContext or RequestContext, so take care to avoidvariable names that overlap with those supplied by your contextprocessors.

If you want context data to take priority over context processors, use thefollowing pattern:

  1. from django.template import RequestContext
  2.  
  3. request_context = RequestContext(request)
  4. request_context.push({"my_name": "Adrian"})

Django does this to allow context data to override context processors inAPIs such as render() andTemplateResponse.

Also, you can give RequestContext a list of additional processors,using the optional, third positional argument, processors. In thisexample, the RequestContext instance gets a ip_address variable:

  1. from django.http import HttpResponse
  2. from django.template import RequestContext, Template
  3.  
  4. def ip_address_processor(request):
  5. return {'ip_address': request.META['REMOTE_ADDR']}
  6.  
  7. def client_ip_view(request):
  8. template = Template('{{ title }}: {{ ip_address }}')
  9. context = RequestContext(request, {
  10. 'title': 'Your IP Address',
  11. }, [ip_address_processor])
  12. return HttpResponse(template.render(context))

Built-in template context processors

Here's what each of the built-in processors does:

django.contrib.auth.context_processors.auth

  • auth()[源代码]
  • If this processor is enabled, every RequestContext will contain thesevariables:

  • user — An auth.User instance representing the currentlylogged-in user (or an AnonymousUser instance, if the client isn'tlogged in).

  • perms — An instance ofdjango.contrib.auth.context_processors.PermWrapper, representing thepermissions that the currently logged-in user has.

django.template.context_processors.debug

  • debug()[源代码]
  • If this processor is enabled, every RequestContext will contain these twovariables — but only if your DEBUG setting is set to True andthe request's IP address (request.META['REMOTE_ADDR']) is in theINTERNAL_IPS setting:

  • debugTrue. You can use this in templates to test whetheryou're in DEBUG mode.

  • sql_queries — A list of {'sql': …, 'time': …} dictionaries,representing every SQL query that has happened so far during the requestand how long it took. The list is in order by database alias and then byquery. It's lazily generated on access.

django.template.context_processors.i18n

  • i18n()[源代码]
  • If this processor is enabled, every RequestContext will contain thesevariables:

  • LANGUAGES — The value of the LANGUAGES setting.

  • LANGUAGE_BIDITrue if the current language is a right-to-leftlanguage, e.g. Hebrew, Arabic. False if it's a left-to-right language,e.g. English, French, German.
  • LANGUAGE_CODErequest.LANGUAGE_CODE, if it exists. Otherwise,the value of the LANGUAGE_CODE setting.
    See i18n template tags for template tags thatgenerate the same values.

django.template.context_processors.media

If this processor is enabled, every RequestContext will contain a variableMEDIA_URL, providing the value of the MEDIA_URL setting.

django.template.context_processors.static

  • static()[源代码]
  • If this processor is enabled, every RequestContext will contain a variableSTATIC_URL, providing the value of the STATIC_URL setting.

django.template.context_processors.csrf

This processor adds a token that is needed by the csrf_token templatetag for protection against Cross Site Request Forgeries.

django.template.context_processors.request

If this processor is enabled, every RequestContext will contain a variablerequest, which is the current HttpRequest.

django.template.context_processors.tz

  • tz()[源代码]
  • If this processor is enabled, every RequestContext will contain a variableTIME_ZONE, providing the name of the currently active time zone.

django.contrib.messages.context_processors.messages

If this processor is enabled, every RequestContext will contain these twovariables:

Writing your own context processors

A context processor has a very simple interface: It's a Python functionthat takes one argument, an HttpRequest object, andreturns a dictionary that gets added to the template context. Each contextprocessor must return a dictionary.

Custom context processors can live anywhere in your code base. All Djangocares about is that your custom context processors are pointed to by the'context_processors' option in your TEMPLATES setting — or thecontext_processors argument of Engine if you'reusing it directly.

Loading templates

Generally, you'll store templates in files on your filesystem rather thanusing the low-level Template API yourself. Savetemplates in a directory specified as a template directory.

Django searches for template directories in a number of places, depending onyour template loading settings (see "Loader types" below), but the most basicway of specifying template directories is by using the DIRS option.

The DIRS option

Tell Django what your template directories are by using the DIRS option in the TEMPLATES setting in your settingsfile — or the dirs argument of Engine. Thisshould be set to a list of strings that contain full paths to your templatedirectories:

  1. TEMPLATES = [
  2. {
  3. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  4. 'DIRS': [
  5. '/home/html/templates/lawrence.com',
  6. '/home/html/templates/default',
  7. ],
  8. },
  9. ]

Your templates can go anywhere you want, as long as the directories andtemplates are readable by the Web server. They can have any extension you want,such as .html or .txt, or they can have no extension at all.

Note that these paths should use Unix-style forward slashes, even on Windows.

Loader types

By default, Django uses a filesystem-based template loader, but Django comeswith a few other template loaders, which know how to load templates from othersources.

Some of these other loaders are disabled by default, but you can activate themby adding a 'loaders' option to your DjangoTemplates backend in theTEMPLATES setting or passing a loaders argument toEngine. loaders should be a list of strings ortuples, where each represents a template loader class. Here are the templateloaders that come with Django:

django.template.loaders.filesystem.Loader

  • class filesystem.Loader
  • Loads templates from the filesystem, according toDIRS.

This loader is enabled by default. However it won't find any templatesuntil you set DIRS to a non-empty list:

  1. TEMPLATES = [{
  2. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  3. 'DIRS': [os.path.join(BASE_DIR, 'templates')],
  4. }]

You can also override 'DIRS' and specify specific directories for aparticular filesystem loader:

  1. TEMPLATES = [{
  2. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  3. 'OPTIONS': {
  4. 'loaders': [
  5. (
  6. 'django.template.loaders.filesystem.Loader',
  7. [os.path.join(BASE_DIR, 'templates')],
  8. ),
  9. ],
  10. },
  11. }]

django.template.loaders.app_directories.Loader

  • class app_directories.Loader
  • Loads templates from Django apps on the filesystem. For each app inINSTALLED_APPS, the loader looks for a templatessubdirectory. If the directory exists, Django looks for templates in there.

This means you can store templates with your individual apps. This alsomakes it easy to distribute Django apps with default templates.

For example, for this setting:

  1. INSTALLED_APPS = ['myproject.polls', 'myproject.music']

…then get_template('foo.html') will look for foo.html in thesedirectories, in this order:

  • /path/to/myproject/polls/templates/
  • /path/to/myproject/music/templates/
    … and will use the one it finds first.

The order of INSTALLED_APPS is significant! For example, if youwant to customize the Django admin, you might choose to override thestandard admin/basesite.html template, from django.contrib.admin,with your own admin/base_site.html in myproject.polls. You mustthen make sure that your myproject.polls comes _beforedjango.contrib.admin in INSTALLED_APPS, otherwisedjango.contrib.admin’s will be loaded first and yours will be ignored.

Note that the loader performs an optimization when it first runs:it caches a list of which INSTALLED_APPS packages have atemplates subdirectory.

You can enable this loader simply by settingAPP_DIRS to True:

  1. TEMPLATES = [{
  2. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  3. 'APP_DIRS': True,
  4. }]

django.template.loaders.cached.Loader

  • class cached.Loader
  • By default (when DEBUG is True), the template system readsand compiles your templates every time they're rendered. While the Djangotemplate system is quite fast, the overhead from reading and compilingtemplates can add up.

You configure the cached template loader with a list of other loaders thatit should wrap. The wrapped loaders are used to locate unknown templateswhen they're first encountered. The cached loader then stores the compiledTemplate in memory. The cached Template instance is returned forsubsequent requests to load the same template.

This loader is automatically enabled if OPTIONS['loaders'] isn't specified and OPTIONS['debug'] is False (the latter option defaults to the valueof DEBUG).

You can also enable template caching with some custom template loadersusing settings like this:

  1. TEMPLATES = [{
  2. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  3. 'DIRS': [os.path.join(BASE_DIR, 'templates')],
  4. 'OPTIONS': {
  5. 'loaders': [
  6. ('django.template.loaders.cached.Loader', [
  7. 'django.template.loaders.filesystem.Loader',
  8. 'django.template.loaders.app_directories.Loader',
  9. 'path.to.custom.Loader',
  10. ]),
  11. ],
  12. },
  13. }]

注解

All of the built-in Django template tags are safe to use with thecached loader, but if you're using custom template tags that come fromthird party packages, or that you wrote yourself, you should ensurethat the Node implementation for each tag is thread-safe. For moreinformation, see template tag thread safety considerations.

django.template.loaders.locmem.Loader

  • class locmem.Loader
  • Loads templates from a Python dictionary. This is useful for testing.

This loader takes a dictionary of templates as its first argument:

  1. TEMPLATES = [{
  2. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  3. 'OPTIONS': {
  4. 'loaders': [
  5. ('django.template.loaders.locmem.Loader', {
  6. 'index.html': 'content here',
  7. }),
  8. ],
  9. },
  10. }]

This loader is disabled by default.

Django uses the template loaders in order according to the 'loaders'option. It uses each loader until a loader finds a match.

Custom loaders

It's possible to load templates from additional sources using custom templateloaders. Custom Loader classes should inherit fromdjango.template.loaders.base.Loader and define the get_contents() andget_template_sources() methods.

Loader methods

  • class Loader[源代码]
  • Loads templates from a given source, such as the filesystem or a database.

    • gettemplate_sources(_template_name)[源代码]
    • A method that takes a template_name and yieldsOrigin instances for each possiblesource.

For example, the filesystem loader may receive 'index.html' as atemplate_name argument. This method would yield origins for thefull path of index.html as it appears in each template directorythe loader looks at.

The method doesn't need to verify that the template exists at a givenpath, but it should ensure the path is valid. For instance, thefilesystem loader makes sure the path lies under a valid templatedirectory.

  • getcontents(_origin)
  • Returns the contents for a template given aOrigin instance.

This is where a filesystem loader would read contents from thefilesystem, or a database loader would read from the database. If amatching template doesn't exist, this should raise aTemplateDoesNotExist error.

The optional skip argument is a list of origins to ignore whenextending templates. This allow templates to extend other templates ofthe same name. It also used to avoid recursion errors.

In general, it is enough to define get_template_sources() andget_contents() for custom template loaders. get_template()will usually not need to be overridden.

Building your own

For examples, read the source code for Django's built-in loaders.

Template origin

Templates have an origin containing attributes depending on the sourcethey are loaded from.

  • class Origin(name, template_name=None, loader=None)[源代码]
    • name
    • The path to the template as returned by the template loader.For loaders that read from the file system, this is the fullpath to the template.

If the template is instantiated directly rather than through atemplate loader, this is a string value of <unknown_source>.

  • template_name
  • The relative path to the template as passed into thetemplate loader.

If the template is instantiated directly rather than through atemplate loader, this is None.

  • loader
  • The template loader instance that constructed this Origin.

If the template is instantiated directly rather than through atemplate loader, this is None.

django.template.loaders.cached.Loader requires all of itswrapped loaders to set this attribute, typically by instantiatingthe Origin with loader=self.