The Django template language: for Python programmersLink to this heading
This document explains the Django template system from a technical perspective -- how it works and how to extend it. If you're just looking for reference on the language syntax, see The Django Template Language.
It assumes an understanding of templates, contexts, variables, tags, and rendering. Start with the introduction to the Django template language if you aren't familiar with these concepts.
オーバービューLink to this heading
Using the template system in Python is a three-step process:
You configure an
Engine.You compile template code into a
Template.You render the template with a
Context.
Django projects generally rely on the high level, backend agnostic APIs for each of these steps instead of the template system's lower level APIs:
For each
DjangoTemplatesbackend in theTEMPLATESsetting, Django instantiates anEngine.DjangoTemplateswrapsEngineand adapts it to the common template backend API.The
django.template.loadermodule provides functions such asget_template()for loading templates. They return adjango.template.backends.django.Templatewhich wraps the actualdjango.template.Template.The
Templateobtained in the previous step has arender()method which marshals a context and possibly a request into aContextand delegates the rendering to the underlyingTemplate.
Configuring an engineLink to this heading
If you are simply using the
DjangoTemplates backend, this
probably isn't the documentation you're looking for. An instance of the
Engine class described below is accessible using the engine attribute
of that backend and any attribute defaults mentioned below are overridden by
what'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)Link to this definition
When instantiating an
Engineall arguments must be passed as keyword arguments:dirsis a list of directories where the engine should look for template source files. It is used to configurefilesystem.Loader.It defaults to an empty list.
app_dirsonly affects the default value ofloaders. See below.It defaults to
False.autoescapecontrols whether HTML autoescaping is enabled.It defaults to
True.context_processorsis a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request. These callables take a request object as their argument and return adictof items to be merged into the context.It defaults to an empty list.
See
RequestContextfor more information.debugis a boolean that turns on/off template debug mode. If it isTrue, the template engine will store additional debug information which can be used to display a detailed report for any exception raised during template rendering.It defaults to
False.loadersis a list of template loader classes, specified as strings. EachLoaderclass knows how to import templates from a particular source. Optionally, a tuple can be used instead of a string. The first item in the tuple should be theLoaderclass name, subsequent items are passed to theLoaderduring initialization.It defaults to a list containing:
'django.template.loaders.filesystem.Loader''django.template.loaders.app_directories.Loader'if and only ifapp_dirsisTrue.
If
debugisFalse, these loaders are wrapped indjango.template.loaders.cached.Loader.See Loader types for details.
string_if_invalidis the output, as a string, that the template system should use for invalid (e.g. misspelled) variables.It defaults to the empty string.
See How invalid variables are handled for details.
file_charsetis the charset used to read template files on disk.It defaults to
'utf-8'.'libraries': A dictionary of labels and dotted Python paths of template tag modules to register with the template engine. This is used to add new libraries or provide alternate labels for existing ones. For example:Engine( libraries={ 'myapp_tags': 'path.to.myapp.tags', 'admin.urls': 'django.contrib.admin.templatetags.admin_urls', }, )Libraries can be loaded by passing the corresponding dictionary key to the
{% load %}tag.'builtins': A list of dotted Python paths of template tag modules to add to built-ins. For example:Engine( builtins=['myapp.builtins'], )Tags and filters from built-in libraries can be used without first calling the
{% load %}tag.
- static Engine.get_default()Link to this definition
When a Django project configures one and only one
DjangoTemplatesengine, this method returns the underlyingEngine. In other circumstances it will raiseImproperlyConfigured.It's required for preserving APIs that rely on a globally available, implicitly configured engine. Any other use is strongly discouraged.
- Engine.from_string(template_code)Link to this definition
Compiles the given template code and returns a
Templateobject.
- Engine.get_template(template_name)Link to this definition
Loads a template with the given name, compiles it and returns a
Templateobject.
- Engine.select_template(template_name_list)Link to this definition
Like
get_template(), except it takes a list of names and returns the first template that was found.
Loading a templateLink to this heading
The recommended way to create a Template is by calling the factory
methods of the Engine: get_template(),
select_template() and from_string().
In a Django project where the TEMPLATES setting defines exactly one
DjangoTemplates engine, it's
possible to instantiate a Template directly.
- class TemplateLink to this definition
This class lives at
django.template.Template. The constructor takes one argument — the raw template code:from django.template import Template template = Template("My name is {{ my_name }}.")
Rendering a contextLink to this heading
Once you have a compiled Template object, you can render a context
with it. You can reuse the same template to render it several times with
different contexts.
- class Context(dict_=None)Link to this definition
The constructor of
django.template.Contexttakes an optional argument — a dictionary mapping variable names to variable values.For details, see Playing with Context objects below.
- Template.render(context)Link to this definition
Call the
Templateobject'srender()method with aContextto "fill" the template:>>> from django.template import Context, Template >>> template = Template("My name is {{ my_name }}.") >>> context = Context({"my_name": "Adrian"}) >>> template.render(context) "My name is Adrian." >>> context = Context({"my_name": "Dolores"}) >>> template.render(context) "My name is Dolores."
Variables and lookupsLink to this heading
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 name signifies a lookup. Specifically, when the template system encounters a dot in a variable name, it tries the following lookups, in this order:
Dictionary lookup. Example:
foo["bar"]Attribute lookup. Example:
foo.barList-index lookup. Example:
foo[bar]
Note that "bar" in a template expression like {{ foo.bar }} will be
interpreted 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-circuit logic. Here are a few examples:
>>> from django.template import Context, Template
>>> t = Template("My name is {{ person.first_name }}.")
>>> d = {"person": {"first_name": "Joe", "last_name": "Johnson"}}
>>> t.render(Context(d))
"My name is Joe."
>>> class PersonClass: pass
>>> p = PersonClass()
>>> p.first_name = "Ron"
>>> p.last_name = "Nasty"
>>> t.render(Context({"person": p}))
"My name is Ron."
>>> t = Template("The first stooge in the list is {{ stooges.0 }}.")
>>> c = Context({"stooges": ["Larry", "Curly", "Moe"]})
>>> t.render(c)
"The first stooge in the list is Larry."
If any part of the variable is callable, the template system will try calling it. Example:
>>> class PersonClass2:
... def name(self):
... return "Samantha"
>>> t = Template("My name is {{ person.name }}.")
>>> t.render(Context({"person": PersonClass2}))
"My name is Samantha."
Callable variables are slightly more complex than variables which only require straight lookups. Here are some things to keep in mind:
If the variable raises an exception when called, the exception will be propagated, unless the exception has an attribute
silent_variable_failurewhose value isTrue. If the exception does have asilent_variable_failureattribute whose value isTrue, the variable will render as the value of the engine'sstring_if_invalidconfiguration option (an empty string, by default). Example:>>> t = Template("My name is {{ person.first_name }}.") >>> class PersonClass3: ... def first_name(self): ... raise AssertionError("foo") >>> p = PersonClass3() >>> t.render(Context({"person": p})) Traceback (most recent call last): ... AssertionError: foo >>> class SilentAssertionError(Exception): ... silent_variable_failure = True >>> class PersonClass4: ... def first_name(self): ... raise SilentAssertionError >>> p = PersonClass4() >>> t.render(Context({"person": p})) "My name is ."Note that
django.core.exceptions.ObjectDoesNotExist, which is the base class for all Django database APIDoesNotExistexceptions, hassilent_variable_failure = True. So if you're using Django templates with Django model objects, anyDoesNotExistexception will fail silently.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, and it'd be either foolish or a security hole to allow the template system to access them.
A good example is the
delete()method on each Django model object. The template system shouldn't be allowed to do something like this:I will now delete this valuable data. {{ data.delete }}To prevent this, set an
alters_dataattribute on the callable variable. The template system won't call a variable if it hasalters_data=Trueset, and will instead replace the variable withstring_if_invalid, unconditionally. The dynamically-generateddelete()andsave()methods on Django model objects getalters_data=Trueautomatically. Example:def sensitive_function(self): self.database_record.delete() sensitive_function.alters_data = TrueOccasionally you may want to turn off this feature for other reasons, and tell the template system to leave a variable uncalled no matter what. To do so, set a
do_not_call_in_templatesattribute on the callable with the valueTrue. The template system then will act as if your variable is not callable (allowing you to access attributes of the callable, for example).
How invalid variables are handledLink to this heading
Generally, if a variable doesn't exist, the template system inserts the value
of 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 if
string_if_invalid is set to '' (the empty string). If
string_if_invalid is set to any other value, variable filters will be
ignored.
This behavior is slightly different for the if, for and regroup
template tags. If an invalid variable is provided to one of these template
tags, the variable will be interpreted as None. Filters are always
applied to invalid variables within these template tags.
If string_if_invalid contains a '%s', the format marker will be
replaced with the name of the invalid variable.
Built-in variablesLink to this heading
Every context contains True, False and None. As you would expect,
these variables resolve to the corresponding Python objects.
Limitations with string literalsLink to this heading
Django's template language has no way to escape the characters used for its own
syntax. For example, the templatetag tag is required if you need to
output character sequences like {% and %}.
A similar issue exists if you want to include these sequences in template filter
or tag arguments. For example, when parsing a block tag, Django's template
parser looks for the first occurrence of %} after a {%. This prevents
the use of "%}" as a string literal. For example, a TemplateSyntaxError
will be raised for the following expressions:
{% include "template.html" tvar="Some string literal with %} in it." %}
{% with tvar="Some string literal with %} in it." %}{% endwith %}
The same issue can be triggered by using a reserved sequence in filter arguments:
{{ some.variable|default:"}}" }}
If you need to use strings with these sequences, store them in template variables or use a custom template tag or filter to workaround the limitation.
Playing with Context objectsLink to this heading
Most of the time, you'll instantiate Context objects by passing in a
fully-populated dictionary to Context(). But you can add and delete items
from a Context object once it's been instantiated, too, using standard
dictionary syntax:
>>> from django.template import Context
>>> c = Context({"foo": "bar"})
>>> c['foo']
'bar'
>>> del c['foo']
>>> c['foo']
Traceback (most recent call last):
...
KeyError: 'foo'
>>> c['newvariable'] = 'hello'
>>> c['newvariable']
'hello'
- Context.get(key, otherwise=None)Link to this definition
Returns the value for
keyifkeyis in the context, else returnsotherwise.
- Context.setdefault(key, default=None)Link to this definition
If
keyis in the context, returns its value. Otherwise insertskeywith a value ofdefaultand returnsdefault.
- Context.pop()Link to this definition
- Context.push()Link to this definition
- exception ContextPopExceptionLink to this definition
A Context object is a stack. That is, you can push() and pop() it.
If you pop() too much, it'll raise
django.template.ContextPopException:
>>> c = Context()
>>> c['foo'] = 'first level'
>>> c.push()
{}
>>> c['foo'] = 'second level'
>>> c['foo']
'second level'
>>> c.pop()
{'foo': 'second level'}
>>> c['foo']
'first level'
>>> c['foo'] = 'overwritten'
>>> c['foo']
'overwritten'
>>> c.pop()
Traceback (most recent call last):
...
ContextPopException
You can also use push() as a context manager to ensure a matching pop()
is called.
>>> c = Context()
>>> c['foo'] = 'first level'
>>> with c.push():
... c['foo'] = 'second level'
... c['foo']
'second level'
>>> c['foo']
'first level'
All arguments passed to push() will be passed to the dict constructor
used to build the new context level.
>>> c = Context()
>>> c['foo'] = 'first level'
>>> with c.push(foo='second level'):
... c['foo']
'second level'
>>> c['foo']
'first level'
- Context.update(other_dict)Link to this definition
In addition to push() and pop(), the Context
object also defines an update() method. This works like push()
but takes a dictionary as an argument and pushes that dictionary onto
the stack instead of an empty one.
>>> c = Context()
>>> c['foo'] = 'first level'
>>> c.update({'foo': 'updated'})
{'foo': 'updated'}
>>> c['foo']
'updated'
>>> c.pop()
{'foo': 'updated'}
>>> c['foo']
'first level'
Like push(), you can use update() as a context manager to ensure a
matching pop() is called.
>>> c = Context()
>>> c['foo'] = 'first level'
>>> with c.update({'foo': 'second level'}):
... c['foo']
'second level'
>>> c['foo']
'first level'
Using a Context as a stack comes in handy in some custom template
tags.
- Context.flatten()Link to this definition
Using flatten() method you can get whole Context stack as one dictionary
including builtin variables.
>>> c = Context()
>>> c['foo'] = 'first level'
>>> c.update({'bar': 'second level'})
{'bar': 'second level'}
>>> c.flatten()
{'True': True, 'None': None, 'foo': 'first level', 'False': False, 'bar': 'second level'}
A flatten() method is also internally used to make Context objects comparable.
>>> c1 = Context()
>>> c1['foo'] = 'first level'
>>> c1['bar'] = 'second level'
>>> c2 = Context()
>>> c2.update({'bar': 'second level', 'foo': 'first level'})
{'foo': 'first level', 'bar': 'second level'}
>>> c1 == c2
True
Result from flatten() can be useful in unit tests to compare Context
against dict:
class ContextTest(unittest.TestCase):
def test_against_dictionary(self):
c1 = Context()
c1['update'] = 'value'
self.assertEqual(c1.flatten(), {
'True': True,
'None': None,
'False': False,
'update': 'value',
})
RequestContext を使うLink to this heading
- class RequestContext(request, dict_=None, processors=None)Link to this definition
Django では特別な Context クラスである django.template.RequestContext が使えます。これは、通常の django.template.Context とはいくつかの点で異なります。最初の違いは、最初の引数として HttpRequest を取ることです。例えば:
c = RequestContext(request, {
'foo': 'bar',
})
2 つめの違いは、エンジンの context_processors 設定オプションによって、昆的に自動的にいくつかの変数をセットすることです。
context_processors オプションは callable -- context processors と呼ばれます -- のリストで、引数としてリクエストオブジェクトを受け取り、コンテキストに統合する項目のディクショナリを返します。 デフォルトで生成される設定ファイルでは、テンプレートエンジンは以下のコンテキストプロセッサを含んでいます:
[
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
]
上記に加えて、RequestContext は常に 'django.template.context_processors.csrf' を使えるようにしています。これは、admin や他の contrib アプリケーションで必要な、セキュリティ関連のコンテキストプロセッサで、設定ミスの場合に備えて意図的にハードコードされており、context_processors オプション内で無効化できないようになっています。
各プロセッサは順番通りに適用されます。したがって、1 番目と 2 番目のプロセッサがそれぞれ同じ名前の変数をコンテキストに追加したとき、2 番目の変数が 1 番目をオーバーライドします。デフォルトのプロセッサは以下で説明します。
また、省略可能な第 3 引数 processors を使って、RequestContext に追加的なプロセッサを渡すこともできます。以下の例では、RequestContext のインスタンスは ip_address 変数を格納します:
from django.http import HttpResponse
from django.template import RequestContext, Template
def ip_address_processor(request):
return {'ip_address': request.META['REMOTE_ADDR']}
def client_ip_view(request):
template = Template('{{ title }}: {{ ip_address }}')
context = RequestContext(request, {
'title': 'Your IP Address',
}, [ip_address_processor])
return HttpResponse(template.render(context))
ビルトインのテンプレートコンテキストプロセッサLink to this heading
以下は、それぞれのビルトインのプロセッサが行うことです:
django.contrib.auth.context_processors.authLink to this heading
- auth()Link to this definition
このプロセッサが有効な場合、全ての RequestContext は以下の変数を含みます:
user--auth.Userのインスタンスで、現在ログイン中のユーザ (あるいはログインしていない場合はAnonymousUserのインスタンス) を表します。perms--django.contrib.auth.context_processors.PermWrapperのインスタンスで、現在ログイン中のユーザが有するパーミッションを表します。
django.template.context_processors.debugLink to this heading
- debug()Link to this definition
このプロセッサが有効な場合、全ての RequestContext は以下の 2 つの変数を含みます -- ただし、 DEBUG 設定が True でリクエストの IP アドレス (request.META['REMOTE_ADDR']) が INTERNAL_IPS 設定内にある場合のみです:
debug--Trueです。DEBUGモードかどうかをテストするためにテンプレート内で使うことができます。sql_queries--{'sql': ..., 'time': ...}ディクショナリのリストで、リクエスト中に発生した全ての SQL クエリとかかった時間を表します。リストはデータベースエイリアス順、クエリ順です。アクセス上でレイジーに生成されます。
django.template.context_processors.i18nLink to this heading
このプロセッサが有効な場合、全ての RequestContext は以下の 2 つの変数を含みます:
LANGUAGES--LANGUAGES設定の値です。LANGUAGE_CODE-- 存在する場合はrequest.LANGUAGE_CODEで、それ以外の場合はLANGUAGE_CODE設定です。
詳しくは 国際化とローカル化 を参照してください。
django.template.context_processors.mediaLink to this heading
このプロセッサが有効な場合、全ての RequestContext は変数 MEDIA_URL を含みます。これは、 MEDIA_URL 設定の値を提供します。
django.template.context_processors.staticLink to this heading
- static()Link to this definition
このプロセッサが有効な場合、全ての RequestContext は変数 STATIC_URL を含みます。これは、STATIC_URL 設定の値を提供します。
django.template.context_processors.csrfLink to this heading
このプロセッサは、 Cross Site Request Forgeries 対策のための csrf_token テンプレートタグが必要とするトークンを追加します。
django.template.context_processors.requestLink to this heading
このプロセッサが有効な場合、全ての RequestContext は変数``request`` を含みます。これは現在の HttpRequest です。
django.template.context_processors.tzLink to this heading
このプロセッサが有効な場合、全ての RequestContext は変数 TIME_ZONE を含みます。これは、現在アクティブなタイムゾーンの名前を提供します。
django.contrib.messages.context_processors.messagesLink to this heading
このプロセッサが有効な場合、全ての RequestContext は以下の 2 つの変数を含みます:
messages-- メッセージフレームワーク を通じてセットされた、(文字列としての) メッセージのリストです。DEFAULT_MESSAGE_LEVELS-- 数値 のメッセージレベル名のマッピングです。
独自のコンテキストプロセッサを記述するLink to this heading
A context processor has a very simple interface: It's a Python function
that takes one argument, an HttpRequest object, and
returns a dictionary that gets added to the template context. Each context
processor must return a dictionary.
Custom context processors can live anywhere in your code base. All Django
cares about is that your custom context processors are pointed to by the
'context_processors' option in your TEMPLATES setting — or the
context_processors argument of Engine if you're
using it directly.
Loading templatesLink to this heading
Generally, you'll store templates in files on your filesystem rather than
using the low-level Template API yourself. Save
templates in a directory specified as a template directory.
Django searches for template directories in a number of places, depending on
your template loading settings (see "Loader types" below), but the most basic
way of specifying template directories is by using the DIRS option.
The DIRS optionLink to this heading
Tell Django what your template directories are by using the DIRS option in the TEMPLATES setting in your settings
file — or the dirs argument of Engine. This
should be set to a list of strings that contain full paths to your template
directories:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
'/home/html/templates/lawrence.com',
'/home/html/templates/default',
],
},
]
Your templates can go anywhere you want, as long as the directories and
templates 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 typesLink to this heading
By default, Django uses a filesystem-based template loader, but Django comes with a few other template loaders, which know how to load templates from other sources.
Some of these other loaders are disabled by default, but you can activate them
by adding a 'loaders' option to your DjangoTemplates backend in the
TEMPLATES setting or passing a loaders argument to
Engine. loaders should be a list of strings or
tuples, where each represents a template loader class. Here are the template
loaders that come with Django:
django.template.loaders.filesystem.Loader
- class filesystem.LoaderLink to this definition
Loads templates from the filesystem, according to
DIRS.This loader is enabled by default. However it won't find any templates until you set
DIRSto a non-empty list:TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], }]You can also override
'DIRS'and specify specific directories for a particular filesystem loader:TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ( 'django.template.loaders.filesystem.Loader', [os.path.join(BASE_DIR, 'templates')], ), ], }, }]
django.template.loaders.app_directories.Loader
- class app_directories.LoaderLink to this definition
Loads templates from Django apps on the filesystem. For each app in
INSTALLED_APPS, the loader looks for atemplatessubdirectory. If the directory exists, Django looks for templates in there.This means you can store templates with your individual apps. This also makes it easy to distribute Django apps with default templates.
For example, for this setting:
INSTALLED_APPS = ['myproject.polls', 'myproject.music']...then
get_template('foo.html')will look forfoo.htmlin these directories, 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_APPSis significant! For example, if you want to customize the Django admin, you might choose to override the standardadmin/base_site.htmltemplate, fromdjango.contrib.admin, with your ownadmin/base_site.htmlinmyproject.polls. You must then make sure that yourmyproject.pollscomes beforedjango.contrib.admininINSTALLED_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_APPSpackages have atemplatessubdirectory.You can enable this loader simply by setting
APP_DIRStoTrue:TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, }]
django.template.loaders.eggs.Loader
- class eggs.LoaderLink to this definition
-
Just like
app_directoriesabove, but it loads templates from Python eggs rather than from the filesystem.This loader is disabled by default.
django.template.loaders.cached.Loader
- class cached.LoaderLink to this definition
By default (when
DEBUGisTrue), the template system reads and compiles your templates every time they're rendered. While the Django template system is quite fast, the overhead from reading and compiling templates can add up.You configure the cached template loader with a list of other loaders that it should wrap. The wrapped loaders are used to locate unknown templates when they're first encountered. The cached loader then stores the compiled
Templatein memory. The cachedTemplateinstance is returned for subsequent requests to load the same template.This loader is automatically enabled if
OPTIONS['loaders']isn't specified andOPTIONS['debug']isFalse(the latter option defaults to the value ofDEBUG).You can also enable template caching with some custom template loaders using settings like this:
TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'OPTIONS': { 'loaders': [ ('django.template.loaders.cached.Loader', [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'path.to.custom.Loader', ]), ], }, }]
django.template.loaders.locmem.Loader
- class locmem.LoaderLink to this definition
Loads templates from a Python dictionary. This is useful for testing.
This loader takes a dictionary of templates as its first argument:
TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': { 'loaders': [ ('django.template.loaders.locmem.Loader', { 'index.html': 'content here', }), ], }, }]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 loadersLink to this heading
It's possible to load templates from additional sources using custom template
loaders. Custom Loader classes should inherit from
django.template.loaders.base.Loader and define the get_contents() and
get_template_sources() methods.
Loader methodsLink to this heading
- class LoaderLink to this definition
Loads templates from a given source, such as the filesystem or a database.
- get_template_sources(template_name)Link to this definition
A method that takes a
template_nameand yieldsOrigininstances for each possible source.For example, the filesystem loader may receive
'index.html'as atemplate_nameargument. This method would yield origins for the full path ofindex.htmlas it appears in each template directory the loader looks at.The method doesn't need to verify that the template exists at a given path, but it should ensure the path is valid. For instance, the filesystem loader makes sure the path lies under a valid template directory.
- get_contents(origin)Link to this definition
Returns the contents for a template given a
Origininstance.This is where a filesystem loader would read contents from the filesystem, or a database loader would read from the database. If a matching template doesn't exist, this should raise a
TemplateDoesNotExisterror.
- get_template(template_name, skip=None)Link to this definition
Returns a
Templateobject for a giventemplate_nameby looping through results fromget_template_sources()and callingget_contents(). This returns the first matching template. If no template is found,TemplateDoesNotExistis raised.The optional
skipargument is a list of origins to ignore when extending templates. This allow templates to extend other templates of the 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.
- load_template_source(template_name, template_dirs=None)Link to this definition
Returns a tuple of (
template_string,template_origin), wheretemplate_stringis a string containing the template contents, andtemplate_originis a string identifying the template source. A filesystem-based loader may return the full path to the file as thetemplate_origin, for example.template_dirsis an optional argument used to control which directories the loader will search.This method is called automatically by
load_template()and should be overridden when writing custom template loaders.
- load_template(template_name, template_dirs=None)Link to this definition
Returns a tuple of (
template,template_origin), wheretemplateis aTemplateobject andtemplate_originis a string identifying the template source. A filesystem-based loader may return the full path to the file as thetemplate_origin, for example.
Template originLink to this heading
Templates have an origin containing attributes depending on the source
they are loaded from.
- class OriginLink to this definition
- nameLink to this definition
The path to the template as returned by the template loader. For loaders that read from the file system, this is the full path to the template.
If the template is instantiated directly rather than through a template loader, this is a string value of
<unknown_source>.
- template_nameLink to this definition
The relative path to the template as passed into the template loader.
If the template is instantiated directly rather than through a template loader, this is
None.