Bahasa cetakan Django: untuk pemrogram Python¶
This document explains the Django template system from a technical perspective -- how it works and how to extend it. If you're looking for reference on the language syntax, see Bahasa cetakan Django.
Diasumsikan sebuah pemahaman dari cetakan, konteks, variabel, etiket, dan membangun. Mulai dengan introduction to the Django template language jika anda tidak akrab dengan konsep ini.
Ikhtisar¶
Menggunakan sistem cetakan dalam Python adalah pengolahan tiga-langkah:
- Anda dapat menkonfigurasi
Engine
. - Anda menyusun kode cetakan kedalam
Template
. - Anda membangun cetakan dengan
Context
.
Proyek Django umumnya bergantung pada high level, backend agnostic APIs untuk setiap langkah-langkah ini daripada API tingkat rendah sistem cetakan:
- For each
DjangoTemplates
backend in theTEMPLATES
setting, Django instantiates anEngine
.DjangoTemplates
wrapsEngine
and adapts it to the common template backend API. - The
django.template.loader
module provides functions such asget_template()
for loading templates. They return adjango.template.backends.django.Template
which wraps the actualdjango.template.Template
. - The
Template
obtained in the previous step has arender()
method which marshals a context and possibly a request into aContext
and delegates the rendering to the underlyingTemplate
.
Mengkonfigurasi mesin¶
If you are 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)¶ When instantiating an
Engine
all arguments must be passed as keyword arguments:dirs
is a list of directories where the engine should look for template source files. It is used to configurefilesystem.Loader
.Itu awalan untuk sebuah list kosong.
app_dirs
hanya mempengaruhi nilai awalandariloaders
. Lihat dibawah.Itu awalan untuk
False
.autoescape
mengendalikan apakah pelolosan otomatis HTML diadakan.Itu awalan untuk
True
.Peringatan
Hanya disetel untuk
False
jika anda sedang membangun cetakan bukan-HTML!context_processors
is 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 adict
of items to be merged into the context.Itu awalan untuk sebuah list kosong.
Lihat
RequestContext
untuk informasi lebih.debug
is 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.Itu awalan untuk
False
.loaders
is a list of template loader classes, specified as strings. EachLoader
class 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 theLoader
class name, subsequent items are passed to theLoader
during initialization.Awalan itu pada sebuah daftar mengandung:
'django.template.loaders.filesystem.Loader'
'django.template.loaders.app_directories.Loader'
jika dan hanya jikaapp_dirs
adalahTrue
.
These loaders are then wrapped in
django.template.loaders.cached.Loader
.Changed in Django 4.1:In older versions, the cached template loader was only enabled by default when
DEBUG
wasFalse
.Lihat Jenis-jenis pemuat untuk lebih rinci.
string_if_invalid
adalah keluaran, sebagai sebuah string, yang sistem cetakan harus menggunakan untuk ketidaksahan variabel (misalnya salah eja).Itu awalan untuk string kosong.
Lihat Bagaimana variabel tidak sah ditangani untuk rincian.
file_charset
is the charset used to read template files on disk.Itu awalan untuk
'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", }, )
Pustaka-pustaka dapat dimuat dengan melewatkan kunci dictionary sesuai ke etiket
{% load %}1
.'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
()¶ Returns the underlying
Engine
from the first configuredDjangoTemplates
engine. RaisesImproperlyConfigured
if no engines are configured.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)¶ Menyusun kode cetakan diberikan dan mengembalikan sebuah obyek
Template
.
-
Engine.
get_template
(template_name)¶ Memuat sebauh cetakan dengan nama diberikan, menyusun itu dan mengembalikan sebuah obyek
Template
.
-
Engine.
select_template
(template_name_list)¶ Seperti
get_template()
, kecuali itu mengambil daftar dari nama-nama dan mengembalikan cetakan pertama yang ditemukan.
Memuat sebuah cetakan¶
Cara dianjurkan untuk membuat Template
adalah dengan memanggil metode pabrik dari Engine
: get_template()
, select_template()
dan from_string()
.
In a Django project where the TEMPLATES
setting defines a
DjangoTemplates
engine, it's
possible to instantiate a Template
directly. If more than one
DjangoTemplates
engine is defined,
the first one will be used.
-
class
Template
¶ Kelas ini tinggal di
django.template.Template
. Pembangun mengambil satu argumen -- kode cetakan mentah:from django.template import Template template = Template("My name is {{ my_name }}.")
Dibalik layar
The system only parses your raw template code once -- when you create the
Template
object. From then on, it's stored internally as a tree
structure for performance.
Bahkan mengurai itu sendiri sangat cepat. Kebanyakan mengurai terjadi melalui panggilan tunggal pada tunggal, pendek, regular expression.
Membangun konteks¶
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)¶ The constructor of
django.template.Context
takes an optional argument — a dictionary mapping variable names to variable values.Untuk rincian, lihat Bermain dengan obyek Context dibawah.
-
Template.
render
(context)¶ Call the
Template
object'srender()
method with aContext
to "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."
Variabel dan pencarian¶
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:
- Pencarian dictionary. Contoh:
foo["bar"]
- Pencarian atribut. Contoh:
foo.bar
- Pencarian index-list. Contoh:
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_failure
whose value isTrue
. If the exception does have asilent_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:>>> 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 APIDoesNotExist
exceptions, hassilent_variable_failure = True
. So if you're using Django templates with Django model objects, anyDoesNotExist
exception 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_invalid
option.
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_data
attribute on the callable variable. The template system won't call a variable if it hasalters_data=True
set, and will instead replace the variable withstring_if_invalid
, unconditionally. The dynamically-generateddelete()
andsave()
methods on Django model objects getalters_data=True
automatically. Example:def sensitive_function(self): self.database_record.delete() 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 matter what. To do so, set a
do_not_call_in_templates
attribute 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).
Bagaimana variabel tidak sah ditangani¶
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.
Hanya untuk tujuan mencari kesalahan!
While string_if_invalid
can be a useful debugging tool, it is a bad
idea to turn it on as a 'development default'.
Many templates, including some of Django's, rely upon the silence of the
template system when a nonexistent variable is encountered. If you assign a
value other than ''
to string_if_invalid
, you will experience
rendering problems with these templates and sites.
Generally, string_if_invalid
should only be enabled in order to debug
a specific template problem, then cleared once debugging is complete.
Variabel siap-pakai¶
Every context contains True
, False
and None
. As you would expect,
these variables resolve to the corresponding Python objects.
Batasan dengan harfiah string¶
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.
Bermain dengan obyek Context
¶
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)¶ Mengembalikan nilai untuk
key
jikakey
berada dalam konteks, lainnya mengembalikanotherwise
.
-
Context.
setdefault
(key, default=None)¶ If
key
is in the context, returns its value. Otherwise insertskey
with a value ofdefault
and returnsdefault
.
-
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 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)¶
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
()¶
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",
},
)
Menggunakan RequestContext
¶
-
class
RequestContext
(request, dict_=None, processors=None)¶
Django comes with a special Context
class,
django.template.RequestContext
, that acts slightly differently from the
normal django.template.Context
. The first difference is that it takes an
HttpRequest
as its first argument. For example:
c = RequestContext(
request,
{
"foo": "bar",
},
)
The second difference is that it automatically populates the context with a
few variables, according to the engine's context_processors
configuration
option.
The context_processors
option is a list of callables -- called context
processors -- that take a request object as their argument and return a
dictionary of items to be merged into the context. In the default generated
settings file, the default template engine contains the following context
processors:
[
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
]
In addition to these, RequestContext
always enables
'django.template.context_processors.csrf'
. This is a security related
context processor required by the admin and other contrib apps, and, in case
of accidental misconfiguration, it is deliberately hardcoded in and cannot be
turned off in the context_processors
option.
Each processor is applied in order. That means, if one processor adds a variable to the context and a second processor adds a variable with the same name, the second will override the first. The default processors are explained below.
Ketika pengolah konteks diberlakukan
Context processors are applied on top of context data. This means that a
context processor may overwrite variables you've supplied to your
Context
or RequestContext
, so take care to avoid
variable names that overlap with those supplied by your context
processors.
If you want context data to take priority over context processors, use the following pattern:
from django.template import RequestContext
request_context = RequestContext(request)
request_context.push({"my_name": "Adrian"})
Django melakukan ini untuk mengizinkan data konteks untuk menimpa pengolah konteks dalam API seperti render()
dan TemplateResponse
.
Also, you can give RequestContext
a list of additional processors,
using the optional, third positional argument, processors
. In this
example, the RequestContext
instance gets an ip_address
variable:
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))
Cetakan siap-pakai pengolah konteks¶
Ini adalah apa setiap dari pengolah siap-pakai lakukan:
django.contrib.auth.context_processors.auth
¶
-
auth
(request)¶
If this processor is enabled, every RequestContext
will contain these
variables:
user
-- Anauth.User
instance representing the currently logged-in user (or anAnonymousUser
instance, if the client isn't logged in).perms
-- An instance ofdjango.contrib.auth.context_processors.PermWrapper
, representing the permissions that the currently logged-in user has.
django.template.context_processors.debug
¶
-
debug
(request)¶
If this processor is enabled, every RequestContext
will contain these two
variables -- but only if your DEBUG
setting is set to True
and
the request's IP address (request.META['REMOTE_ADDR']
) is in the
INTERNAL_IPS
setting:
debug
--True
. You can use this in templates to test whether you're inDEBUG
mode.sql_queries
-- A list of{'sql': ..., 'time': ...}
dictionaries, representing every SQL query that has happened so far during the request and how long it took. The list is in order by database alias and then by query. It's lazily generated on access.
django.template.context_processors.i18n
¶
-
i18n
(request)¶
If this processor is enabled, every RequestContext
will contain these
variables:
LANGUAGES
-- Nilai dari pengaturanLANGUAGES
.LANGUAGE_BIDI
--True
if the current language is a right-to-left language, e.g. Hebrew, Arabic.False
if it's a left-to-right language, e.g. English, French, German.LANGUAGE_CODE
--request.LANGUAGE_CODE
, jika dia ada. Sebaliknya, nilai dari pengaturanLANGUAGE_CODE
.
Lihat i18n template tags untuk etiket cetakan yang membangkitkan nilai-nilai sama.
django.template.context_processors.media
¶
If this processor is enabled, every RequestContext
will contain a variable
MEDIA_URL
, providing the value of the MEDIA_URL
setting.
django.template.context_processors.static
¶
-
static
(request)¶
If this processor is enabled, every RequestContext
will contain a variable
STATIC_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
template
tag for protection against Cross Site Request Forgeries.
django.template.context_processors.request
¶
Jika pengolah ini diadakan, setiap RequestContext
akan mengandung sebuah variabel request
, dimana kelas saat ini HttpRequest
.
django.template.context_processors.tz
¶
-
tz
(request)¶
If this processor is enabled, every RequestContext
will contain a variable
TIME_ZONE
, providing the name of the currently active time zone.
django.contrib.messages.context_processors.messages
¶
Jika pengolah ini diadakan, setiap RequestContext
akan mengandung dua variabel ini:
messages
-- Sebuah daftar dari pesan-pesan (sebagai string) yang telah disetel melalui messages framework.DEFAULT_MESSAGE_LEVELS
-- Sebuah pemetaan dari tingkat pesan nama untuk their numeric value.
menulis pengolah konteks anda sendiri¶
A context processor has a 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.
For example, to add the DEFAULT_FROM_EMAIL
setting to every
context:
from django.conf import settings
def from_email(request):
return {
"DEFAULT_FROM_EMAIL": settings.DEFAULT_FROM_EMAIL,
}
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.
Memuat cetakan¶
Umumnya, anda akan menyimpan cetakan-cetakan dalam berkas pada sistem berkas anda daripada menggunakan API tingkat-rendah Template
anda sendiri. Simpanc etakan-cetakan dalam sebuah direktori ditentukan sebagai sebuah 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.
Pilihan DIRS
¶
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.
Catat bahwa jalur-jalur ini harus menggunakan garis miring didepan gaya-Unix, bahkan pada Windows.
Jenis-jenis pemuat¶
Secara awal, Django menggunakan pemuat cetakan bedasarkan sistem berkas, tetapi Django datang dengan sedikit pemuat cetakan lain, uang mengetahui bagaimana memuat cetakan dari sumber-sumber lain.
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.
Loader
¶ Memuat cetakan dari sistem berkas, menurut pada
DIRS
.This loader is enabled by default. However it won't find any templates until you set
DIRS
to a non-empty list:TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [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", [BASE_DIR / "templates"], ), ], }, } ]
django.template.loaders.app_directories.Loader
-
class
app_directories.
Loader
¶ Loads templates from Django apps on the filesystem. For each app in
INSTALLED_APPS
, the loader looks for atemplates
subdirectory. If the directory exists, Django looks for templates in there.This means you can store templates with your individual apps. This also helps to distribute Django apps with default templates.
Sebagai contoh, untuk pengaturan ini:
INSTALLED_APPS = ["myproject.polls", "myproject.music"]
...then
get_template('foo.html')
will look forfoo.html
in these directories, in this order:/path/to/myproject/polls/templates/
/path/to/myproject/music/templates/
... dan akan menggunakan satu itu temukan pertama kali.
The order of
INSTALLED_APPS
is significant! For example, if you want to customize the Django admin, you might choose to override the standardadmin/base_site.html
template, fromdjango.contrib.admin
, with your ownadmin/base_site.html
inmyproject.polls
. You must then make sure that yourmyproject.polls
comes beforedjango.contrib.admin
inINSTALLED_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 by setting
APP_DIRS
toTrue
:TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, } ]
django.template.loaders.cached.Loader
-
class
cached.
Loader
¶ While the Django template system is quite fast, if it needs to read and compile your templates every time they're rendered, the overhead from that 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
Template
in memory. The cachedTemplate
instance is returned for subsequent requests to load the same template.This loader is automatically enabled if
OPTIONS['loaders']
isn't specified.You can manually specify template caching with some custom template loaders using settings like this:
TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [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", ], ), ], }, } ]
Catatan
All of the built-in Django template tags are safe to use with the cached loader, but if you're using custom template tags that come from third party packages, or that you wrote yourself, you should ensure that the
Node
implementation for each tag is thread-safe. For more information, see template tag thread safety considerations.Changed in Django 4.1:The cached template loader was enabled whenever
OPTIONS['loaders']
is not specified. Previously it was only enabled whenDEBUG
wasFalse
.
django.template.loaders.locmem.Loader
-
class
locmem.
Loader
¶ Memuat cetakan-cetakan dari sebuah kamus Python. Ini berguna untuk percobaan.
Pemuat ini mengambil sebuah dictionary dari cetakan sebagai argumen pertamanya:
TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "OPTIONS": { "loaders": [ ( "django.template.loaders.locmem.Loader", { "index.html": "content here", }, ), ], }, } ]
Pemuat ini ditiadakan secara awalan.
Django uses the template loaders in order according to the 'loaders'
option. It uses each loader until a loader finds a match.
Pemuat penyesuaian¶
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.
Metode-metode pemuat¶
-
class
Loader
¶ Memuat cetakan-cetakan dari sumber diberikan, seperti sistem berkas atau sebuah basisdata.
-
get_template_sources
(template_name)¶ A method that takes a
template_name
and yieldsOrigin
instances for each possible source.For example, the filesystem loader may receive
'index.html'
as atemplate_name
argument. This method would yield origins for the full path ofindex.html
as 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)¶ Mengembalikan isi untuk sebuah cetakan untuk cetakan diberikan instance
Origin
.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
TemplateDoesNotExist
error.
-
get_template
(template_name, skip=None)¶ Returns a
Template
object for a giventemplate_name
by looping through results fromget_template_sources()
and callingget_contents()
. This returns the first matching template. If no template is found,TemplateDoesNotExist
is raised.The optional
skip
argument 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.
-
Membangun milik anda
Sebagai contoh, baca source code for Django's built-in loaders.
Cetakan asli¶
Templates have an origin
containing attributes depending on the source
they 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 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_name
¶ Jalur relatif pada cetakan dilewatkan kedalam pemuat cetakan.
Jika cetakan diinstansiasi langsung daripada melalui sebuah pemuat cetakan, ini adalah
None
.
-
loader
¶ Instance pemuat cetakan yang membangun
Origin
ini.Jika cetakan diinstansiasi langsung daripada melalui sebuah pemuat cetakan, ini adalah
None
.django.template.loaders.cached.Loader
requires all of its wrapped loaders to set this attribute, typically by instantiating theOrigin
withloader=self
.
-