模板

作为一个Web框架,Django需要一种动态生成HTML的便捷方法。最常用的方法依赖于模板。模板包含所需HTML输出的静态部分以及描述动态内容将被插入的一些特殊语法。有关创建带有模板的HTML页面的示例,请参阅:doc:`Tutorial 3</intro/tutorial03>

Django项目可以配置一个或多个模板引擎(或者如果不使用模板,甚至为零)。Django后端内置一个自己的模板系统,创造性地称为Django template language(DTL),和一个流行的替代品JICAN2*。后端也可以使用第三方提供其他可用的模板语言。

Django定义了一个标准的API,用于加载和渲染模板,而不用考虑后端的模板系统。加载包括查找给定标识符的模板并对其进行预处理,通常将其编译的结果保存在内存中。渲染工具将上下文数据插入模板并返回结果字符串。

Doc:Django template language </ref/templates/language>是Django自己的模板系统。直到Django 1.8,它是唯一可用的内置选项。这是一个很好的模板库,即使它是相当僵硬和使用时带有它自己特质。如果您没有紧迫的理由需要去选择另一个后端,则应该使用DTL,特别是如果您正在编写可插入的应用程序并打算分发模板。在 Django's contrib apps 中的有些模板,比如:doc:`django.contrib.admin </ref/contrib/admin/index>,使用DTL。

由于历史原因,模板引擎的通用支持和Django模板语言的实现都存在于django.template 模块的命名空间中。

警告

模板系统使用不可信的模板作者的模板是不安全的。例如,一个站点不应该允许它的用户提供他们自己的模板,因为模板作者可以做一些事情,比如执行XSS攻击和拿到包含敏感信息的模板变量的访问权。

模板引擎的支持

配置

Templates engines are configured with the TEMPLATES setting. It's alist of configurations, one for each engine. The default value is empty. Thesettings.py generated by the startproject command defines amore useful value:

  1. TEMPLATES = [
  2. {
  3. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  4. 'DIRS': [],
  5. 'APP_DIRS': True,
  6. 'OPTIONS': {
  7. # ... some options here ...
  8. },
  9. },
  10. ]

BACKEND is a dotted Python path to a templateengine class implementing Django's template backend API. The built-in backendsare django.template.backends.django.DjangoTemplates anddjango.template.backends.jinja2.Jinja2.

Since most engines load templates from files, the top-level configuration foreach engine contains two common settings:

  • DIRS defines a list of directories where theengine should look for template source files, in search order.
  • APP_DIRS tells whether the engine shouldlook for templates inside installed applications. Each backend defines aconventional name for the subdirectory inside applications where itstemplates should be stored.While uncommon, it's possible to configure several instances of the samebackend with different options. In that case you should define a uniqueNAME for each engine.

OPTIONS contains backend-specific settings.

用法

The django.template.loader module defines two functions to load templates.

  • gettemplate(_template_name, using=None)[源代码]
  • This function loads the template with the given name and returns aTemplate object.

The exact type of the return value depends on the backend that loaded thetemplate. Each backend has its own Template class.

get_template() tries each template engine in order until one succeeds.If the template cannot be found, it raisesTemplateDoesNotExist. If the template is found butcontains invalid syntax, it raisesTemplateSyntaxError.

How templates are searched and loaded depends on each engine's backend andconfiguration.

If you want to restrict the search to a particular template engine, passthe engine's NAME in the using argument.

  • selecttemplate(_template_name_list, using=None)[源代码]
  • select_template() is just like get_template(), except it takes alist of template names. It tries each name in order and returns the firsttemplate that exists.

If loading a template fails, the following two exceptions, defined indjango.template, may be raised:

  • exception TemplateDoesNotExist(msg, tried=None, backend=None, chain=None)[源代码]
  • This exception is raised when a template cannot be found. It accepts thefollowing optional arguments for populating the template postmortem on the debug page:

    • backend
    • The template backend instance from which the exception originated.
    • tried
    • A list of sources that were tried when finding the template. This isformatted as a list of tuples containing (origin, status), whereorigin is an origin-like object andstatus is a string with the reason the template wasn't found.
    • chain
    • A list of intermediate TemplateDoesNotExistexceptions raised when trying to load a template. This is used byfunctions, such as get_template(), thattry to load a given template from multiple engines.
  • exception TemplateSyntaxError(msg)[源代码]
  • This exception is raised when a template was found but contains errors.

Template objects returned by get_template() and select_template()must provide a render() method with the following signature:

  • Template.render(context=None, request=None)
  • Renders this template with a given context.

If context is provided, it must be a dict. If it isn'tprovided, the engine will render the template with an empty context.

If request is provided, it must be an HttpRequest.Then the engine must make it, as well as the CSRF token, available in thetemplate. How this is achieved is up to each backend.

Here's an example of the search algorithm. For this example theTEMPLATES setting is:

  1. TEMPLATES = [
  2. {
  3. 'BACKEND': 'django.template.backends.django.DjangoTemplates',
  4. 'DIRS': [
  5. '/home/html/example.com',
  6. '/home/html/default',
  7. ],
  8. },
  9. {
  10. 'BACKEND': 'django.template.backends.jinja2.Jinja2',
  11. 'DIRS': [
  12. '/home/html/jinja2',
  13. ],
  14. },
  15. ]

If you call get_template('story_detail.html'), here are the files Djangowill look for, in order:

  • /home/html/example.com/story_detail.html ('django' engine)
  • /home/html/default/story_detail.html ('django' engine)
  • /home/html/jinja2/story_detail.html ('jinja2' engine)If you call select_template(['story_253_detail.html', 'story_detail.html']),here's what Django will look for:

  • /home/html/example.com/story_253_detail.html ('django' engine)

  • /home/html/default/story_253_detail.html ('django' engine)
  • /home/html/jinja2/story_253_detail.html ('jinja2' engine)
  • /home/html/example.com/story_detail.html ('django' engine)
  • /home/html/default/story_detail.html ('django' engine)
  • /home/html/jinja2/story_detail.html ('jinja2' engine)When Django finds a template that exists, it stops looking.

Tip

You can use select_template() for flexibletemplate loading. For example, if you've written a news story and wantsome stories to have custom templates, use something likeselecttemplate(['story%s_detail.html' % story.id,'story_detail.html']). That'll allow you to use a custom template for anindividual story, with a fallback template for stories that don't havecustom templates.

It's possible — and preferable — to organize templates in subdirectoriesinside each directory containing templates. The convention is to make asubdirectory for each Django app, with subdirectories within thosesubdirectories as needed.

Do this for your own sanity. Storing all templates in the root level of asingle directory gets messy.

To load a template that's within a subdirectory, just use a slash, like so:

  1. get_template('news/story_detail.html')

Using the same TEMPLATES option as above, this will attempt to loadthe following templates:

  • /home/html/example.com/news/story_detail.html ('django' engine)
  • /home/html/default/news/story_detail.html ('django' engine)
  • /home/html/jinja2/news/story_detail.html ('jinja2' engine)此外,为了减少加载和渲染模板的重复性,Django 提供了一个自动处理的快捷函数。

  • renderto_string(_template_name, context=None, request=None, using=None)[源代码]

  • render_to_string() 加载一个模板 get_template() ,并立即调用它的 render() 方法。它需要下面的参数。

    • template_name
    • 加载和呈现模板的名称。如果是模板名称列表,Django 使用 select_template() ,而不是 get_template() 找到模板。
    • context
    • dict 用作模板的渲染上下文。
    • request
    • 可选项 HttpRequest 在模板的渲染过程中可用。
    • using
    • 可选的模板引擎 NAME。对模板的搜索将限于该引擎。使用实例:
  1. from django.template.loader import render_to_string
  2. rendered = render_to_string('my_template.html', {'foo': 'bar'})

还可以参看 render() 快捷函数,它调用 render_to_string() ,并将结果提供给 HttpResponse ,适合从视图返回。

最后,您可以直接使用配置好的引擎:

  • engines
  • 模板引擎可在 django.template.engines 中使用:
  1. from django.template import engines
  2.  
  3. django_engine = engines['django']
  4. template = django_engine.from_string("Hello {{ name }}!")

在这个例子中,查找关键字“django”是引擎的 NAME

内置后端

  • class DjangoTemplates[源代码]
  • 设置 BACKEND'django.template.backends.django.DjangoTemplates',以配置 Django 模板引擎。

When APP_DIRS is True, DjangoTemplatesengines look for templates in the templates subdirectory of installedapplications. This generic name was kept for backwards-compatibility.

DjangoTemplates engines accept the following OPTIONS:

  • 'autoescape': a boolean that controls whether HTML autoescaping isenabled.

It defaults to True.

警告

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

  • 'context_processors': a list of dotted Python paths to callables thatare 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.

It defaults to an empty list.

See RequestContext for more information.

  • 'debug': a boolean that turns on/off template debug mode. If it isTrue, the fancy error page will display a detailed report for anyexception raised during template rendering. This report contains therelevant snippet of the template with the appropriate line highlighted.

It defaults to the value of the DEBUG setting.

  • 'loaders': a list of dotted Python paths to template loader classes.Each Loader class knows how to import templates from a particularsource. Optionally, a tuple can be used instead of a string. The first itemin the tuple should be the Loader class name, and subsequent items arepassed to the Loader during initialization.

The default depends on the values of DIRS andAPP_DIRS.

See Loader types for details.

  • 'string_if_invalid': the output, as a string, that the template systemshould use for invalid (e.g. misspelled) variables.

It defaults to an empty string.

See How invalid variables are handled for details.

  • 'file_charset': 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 can be used to addnew libraries or provide alternate labels for existing ones. For example:
  1. OPTIONS={
  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. OPTIONS={
  2. 'builtins': ['myapp.builtins'],
  3. }

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

  1. $ pip install Jinja2
  1. ...\> pip install Jinja2

Set BACKEND to'django.template.backends.jinja2.Jinja2' to configure a Jinja2 engine.

When APP_DIRS is True, Jinja2 engineslook for templates in the jinja2 subdirectory of installed applications.

The most important entry in OPTIONS is'environment'. It's a dotted Python path to a callable returning a Jinja2environment. It defaults to 'jinja2.Environment'. Django invokes thatcallable and passes other options as keyword arguments. Furthermore, Djangoadds defaults that differ from Jinja2's for a few options:

  • 'autoescape': True
  • 'loader': a loader configured for DIRS andAPP_DIRS
  • 'auto_reload': settings.DEBUG
  • 'undefined': DebugUndefined if settings.DEBUG else UndefinedJinja2 engines also accept the following OPTIONS:

  • 'context_processors': a list of dotted Python paths to callables thatare 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.

It defaults to an empty list.

Using context processors with Jinja2 templates is discouraged.

Context processors are useful with Django templates because Django templatesdon't support calling functions with arguments. Since Jinja2 doesn't havethat limitation, it's recommended to put the function that you would use as acontext processor in the global variables available to the template usingjinja2.Environment as described below. You can then call that function inthe template:

  1. {{ function(request) }}

Some Django templates context processors return a fixed value. For Jinja2templates, this layer of indirection isn't necessary since you can addconstants directly in jinja2.Environment.

The original use case for adding context processors for Jinja2 involved:

  • Making an expensive computation that depends on the request.
  • Needing the result in every template.
  • Using the result multiple times in each template.Unless all of these conditions are met, passing a function to the template issimpler and more in line with the design of Jinja2.

The default configuration is purposefully kept to a minimum. If a template isrendered with a request (e.g. when using render()),the Jinja2 backend adds the globals request, csrf_input, andcsrf_token to the context. Apart from that, this backend doesn't create aDjango-flavored environment. It doesn't know about Django filters and tags.In order to use Django-specific APIs, you must configure them into theenvironment.

For example, you can create myproject/jinja2.py with this content:

  1. from django.templatetags.static import static
  2. from django.urls import reverse
  3.  
  4. from jinja2 import Environment
  5.  
  6.  
  7. def environment(**options):
  8. env = Environment(**options)
  9. env.globals.update({
  10. 'static': static,
  11. 'url': reverse,
  12. })
  13. return env

and set the 'environment' option to 'myproject.jinja2.environment'.

Then you could use the following constructs in Jinja2 templates:

  1. <img src="{{ static('path/to/company-logo.png') }}" alt="Company Logo">
  2.  
  3. <a href="{{ url('admin:index') }}">Administration</a>

The concepts of tags and filters exist both in the Django template languageand in Jinja2 but they're used differently. Since Jinja2 supports passingarguments to callables in templates, many features that require a template tagor filter in Django templates can be achieved simply by calling a function inJinja2 templates, as shown in the example above. Jinja2's global namespaceremoves the need for template context processors. The Django template languagedoesn't have an equivalent of Jinja2 tests.

Custom backends

Here's how to implement a custom template backend in order to use anothertemplate system. A template backend is a class that inheritsdjango.template.backends.base.BaseEngine. It must implementget_template() and optionally from_string(). Here's an example for afictional foobar template library:

  1. from django.template import TemplateDoesNotExist, TemplateSyntaxError
  2. from django.template.backends.base import BaseEngine
  3. from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy
  4.  
  5. import foobar
  6.  
  7.  
  8. class FooBar(BaseEngine):
  9.  
  10. # Name of the subdirectory containing the templates for this engine
  11. # inside an installed application.
  12. app_dirname = 'foobar'
  13.  
  14. def __init__(self, params):
  15. params = params.copy()
  16. options = params.pop('OPTIONS').copy()
  17. super().__init__(params)
  18.  
  19. self.engine = foobar.Engine(**options)
  20.  
  21. def from_string(self, template_code):
  22. try:
  23. return Template(self.engine.from_string(template_code))
  24. except foobar.TemplateCompilationFailed as exc:
  25. raise TemplateSyntaxError(exc.args)
  26.  
  27. def get_template(self, template_name):
  28. try:
  29. return Template(self.engine.get_template(template_name))
  30. except foobar.TemplateNotFound as exc:
  31. raise TemplateDoesNotExist(exc.args, backend=self)
  32. except foobar.TemplateCompilationFailed as exc:
  33. raise TemplateSyntaxError(exc.args)
  34.  
  35.  
  36. class Template:
  37.  
  38. def __init__(self, template):
  39. self.template = template
  40.  
  41. def render(self, context=None, request=None):
  42. if context is None:
  43. context = {}
  44. if request is not None:
  45. context['request'] = request
  46. context['csrf_input'] = csrf_input_lazy(request)
  47. context['csrf_token'] = csrf_token_lazy(request)
  48. return self.template.render(context)

See DEP 182 for more information.

Debug integration for custom engines

The Django debug page has hooks to provide detailed information when a templateerror arises. Custom template engines can use these hooks to enhance thetraceback information that appears to users. The following hooks are available:

Template postmortem

The postmortem appears when TemplateDoesNotExist israised. It lists the template engines and loaders that were used when tryingto find a given template. For example, if two Django engines are configured,the postmortem will appear like:../../_images/postmortem.pngCustom engines can populate the postmortem by passing the backend andtried arguments when raising TemplateDoesNotExist.Backends that use the postmortem should specify an origin on the template object.

Contextual line information

If an error happens during template parsing or rendering, Django can displaythe line the error happened on. For example:../../_images/template-lines.pngCustom engines can populate this information by setting a template_debugattribute on exceptions raised during parsing and rendering. This attributeis a dict with the following values:

  • 'name': The name of the template in which the exception occurred.
  • 'message': The exception message.
  • 'source_lines': The lines before, after, and including the line theexception occurred on. This is for context, so it shouldn't contain more than20 lines or so.
  • 'line': The line number on which the exception occurred.
  • 'before': The content on the error line before the token that raised theerror.
  • 'during': The token that raised the error.
  • 'after': The content on the error line after the token that raised theerror.
  • 'total': The number of lines in source_lines.
  • 'top': The line number where source_lines starts.
  • 'bottom': The line number where source_lines ends.Given the above template error, template_debug would look like:
  1. {
  2. 'name': '/path/to/template.html',
  3. 'message': "Invalid block tag: 'syntax'",
  4. 'source_lines': [
  5. (1, 'some\n'),
  6. (2, 'lines\n'),
  7. (3, 'before\n'),
  8. (4, 'Hello {% syntax error %} {{ world }}\n'),
  9. (5, 'some\n'),
  10. (6, 'lines\n'),
  11. (7, 'after\n'),
  12. (8, ''),
  13. ],
  14. 'line': 4,
  15. 'before': 'Hello ',
  16. 'during': '{% syntax error %}',
  17. 'after': ' {{ world }}\n',
  18. 'total': 9,
  19. 'bottom': 9,
  20. 'top': 1,
  21. }

Origin API and 3rd-party integration

Django templates have an Origin object availablethrough the template.origin attribute. This enables debug information to bedisplayed in the template postmortem, as well asin 3rd-party libraries, like the Django Debug Toolbar.

Custom engines can provide their own template.origin information bycreating an object that specifies the following attributes:

  • 'name': The full path to the template.
  • 'template_name': The relative path to the template as passed into thethe template loading methods.
  • 'loader_name': An optional string identifying the function or class usedto load the template, e.g. django.template.loaders.filesystem.Loader.

The Django template language

Syntax

About this section

This is an overview of the Django template language's syntax. For detailssee the language syntax reference.

A Django template is simply a text document or a Python string marked-up usingthe Django template language. Some constructs are recognized and interpretedby the template engine. The main ones are variables and tags.

A template is rendered with a context. Rendering replaces variables with theirvalues, which are looked up in the context, and executes tags. Everything elseis output as is.

The syntax of the Django template language involves four constructs.

变量

A variable outputs a value from the context, which is a dict-like objectmapping keys to values.

Variables are surrounded by {{ and }} like this:

  1. My first name is {{ first_name }}. My last name is {{ last_name }}.

With a context of {'first_name': 'John', 'last_name': 'Doe'}, thistemplate renders to:

  1. My first name is John. My last name is Doe.

Dictionary lookup, attribute lookup and list-index lookups are implementedwith a dot notation:

  1. {{ my_dict.key }}
  2. {{ my_object.attribute }}
  3. {{ my_list.0 }}

If a variable resolves to a callable, the template system will call it with noarguments and use its result instead of the callable.

标签(Tags)

Tags provide arbitrary logic in the rendering process.

This definition is deliberately vague. For example, a tag can output content,serve as a control structure e.g. an "if" statement or a "for" loop, grabcontent from a database, or even enable access to other template tags.

Tags are surrounded by {% and %} like this:

  1. {% csrf_token %}

Most tags accept arguments:

  1. {% cycle 'odd' 'even' %}

Some tags require beginning and ending tags:

  1. {% if user.is_authenticated %}Hello, {{ user.username }}.{% endif %}

A reference of built-in tags isavailable as well as instructions for writing custom tags.

过滤器

Filters transform the values of variables and tag arguments.

They look like this:

  1. {{ django|title }}

With a context of {'django': 'the web framework for perfectionists withdeadlines'}, this template renders to:

  1. The Web Framework For Perfectionists With Deadlines

Some filters take an argument:

  1. {{ my_date|date:"Y-m-d" }}

A reference of built-in filters isavailable as well as instructions for writing custom filters.

注释(Comments)

Comments look like this:

  1. {# this won't be rendered #}

A {% comment %} tag provides multi-line comments.

Components

About this section

This is an overview of the Django template language's APIs. For detailssee the API reference.

Engine

django.template.Engine encapsulates an instance of the Djangotemplate system. The main reason for instantiating anEngine directly is to use the Django templatelanguage outside of a Django project.

django.template.backends.django.DjangoTemplates is a thin wrapperadapting django.template.Engine to Django's template backend API.

Template

django.template.Template represents a compiled template.Templates are obtained with Engine.get_template() or Engine.from_string()

Likewise django.template.backends.django.Template is a thin wrapperadapting django.template.Template to the common template API.

Context

django.template.Context holds some metadata in addition to thecontext data. It is passed to Template.render() for rendering a template.

django.template.RequestContext is a subclass ofContext that stores the currentHttpRequest and runs template context processors.

The common API doesn't have an equivalent concept. Context data is passed in aplain dict and the current HttpRequest is passedseparately if needed.

Loaders

Template loaders are responsible for locating templates, loading them, andreturning Template objects.

Django provides several built-in template loadersand supports custom template loaders.

Context processors

Context processors are functions that receive the currentHttpRequest as an argument and return a dict ofdata to be added to the rendering context.

Their main use is to add common data shared by all templates to the contextwithout repeating code in every view.

Django provides many built-in context processors.Implementing a custom context processor is as simple as defining a function.