{"title":"模板","version":"2.0","locale":"zh-hans","docname":"topics/templates","url":"/zh-hans/2.0/topics/templates/","canonical":"https://djangodocs.dev/zh-hans/2.0/topics/templates/","summary":"作为一个Web框架，Django需要一种动态生成HTML的便捷方法。最常用的方法依赖于模板。模板包含所需HTML输出的静态部分以及描述动态内容将被插入的一些特殊语法。有关创建带有模板的HTML页面的示例，请参阅:doc: ` Tutorial 3</intro/tutorial03>…","html":"<span id=\"templates\"></span><h1>模板<a class=\"heading-anchor\" href=\"#module-django.template\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h1>\n<p>作为一个Web框架，Django需要一种动态生成HTML的便捷方法。最常用的方法依赖于模板。模板包含所需HTML输出的静态部分以及描述动态内容将被插入的一些特殊语法。有关创建带有模板的HTML页面的示例，请参阅:doc:<a href=\"#id1\"><span class=\"problematic\" id=\"id2\">`</span></a>Tutorial 3&lt;/intro/tutorial03&gt;</p>\n<p>Django项目可以配置一个或多个模板引擎（或者如果不使用模板，甚至为零）。Django后端内置一个自己的模板系统，创造性地称为Django template language（DTL），和一个流行的替代品JICAN2*。后端也可以使用第三方提供其他可用的模板语言。</p>\n<p>Django定义了一个标准的API，用于加载和渲染模板，而不用考虑后端的模板系统。加载包括查找给定标识符的模板并对其进行预处理，通常将其编译的结果保存在内存中。渲染工具将上下文数据插入模板并返回结果字符串。</p>\n<p>Doc：Django template language &lt;/ref/templates/language&gt;是Django自己的模板系统。直到Django 1.8，它是唯一可用的内置选项。这是一个很好的模板库，即使它是相当僵硬和使用时带有它自己特质。如果您没有紧迫的理由需要去选择另一个后端，则应该使用DTL，特别是如果您正在编写可插入的应用程序并打算分发模板。在 Django's contrib apps 中的有些模板，比如:doc:<a href=\"#id1\"><span class=\"problematic\" id=\"id2\">`</span></a>django.contrib.admin &lt;/ref/contrib/admin/index&gt;，使用DTL。</p>\n<p>由于历史原因，模板引擎的通用支持和Django模板语言的实现都存在于``django.template`` 模块的命名空间中。</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Warning</p>\n<p>模板系统使用不可信的模板作者的模板是不安全的。例如，一个站点不应该允许它的用户提供他们自己的模板，因为模板作者可以做一些事情，比如执行XSS攻击和拿到包含敏感信息的模板变量的访问权。</p>\n</aside>\n<section id=\"support-for-template-engines\">\n<span id=\"template-engines\"></span><h2>模板引擎的支持<a class=\"heading-anchor\" href=\"#support-for-template-engines\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<section id=\"configuration\">\n<h3>配置<a class=\"heading-anchor\" href=\"#configuration\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Templates engines are configured with the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES\"><code class=\"xref std std-setting docutils literal notranslate\">TEMPLATES</code></a> setting. It's a\nlist of configurations, one for each engine. The default value is empty. The\n<code class=\"docutils literal notranslate\">settings.py</code> generated by the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/django-admin/#django-admin-startproject\"><code class=\"xref std std-djadmin docutils literal notranslate\">startproject</code></a> command defines a\nmore useful value:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>TEMPLATES <span class=\"o\">=</span> <span class=\"p\">[</span>\n    <span class=\"p\">{</span>\n        <span class=\"s1\">&#39;BACKEND&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;django.template.backends.django.DjangoTemplates&#39;</span><span class=\"p\">,</span>\n        <span class=\"s1\">&#39;DIRS&#39;</span><span class=\"p\">:</span> <span class=\"p\">[],</span>\n        <span class=\"s1\">&#39;APP_DIRS&#39;</span><span class=\"p\">:</span> <span class=\"kc\">True</span><span class=\"p\">,</span>\n        <span class=\"s1\">&#39;OPTIONS&#39;</span><span class=\"p\">:</span> <span class=\"p\">{</span>\n            <span class=\"c1\"># ... some options here ...</span>\n        <span class=\"p\">},</span>\n    <span class=\"p\">},</span>\n<span class=\"p\">]</span>\n</code></pre></div>\n<p><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-BACKEND\"><code class=\"xref std std-setting docutils literal notranslate\">BACKEND</code></a> is a dotted Python path to a template\nengine class implementing Django's template backend API. The built-in backends\nare <a class=\"reference internal\" href=\"#django.template.backends.django.DjangoTemplates\" title=\"django.template.backends.django.DjangoTemplates\"><code class=\"xref py py-class docutils literal notranslate\">django.template.backends.django.DjangoTemplates</code></a> and\n<a class=\"reference internal\" href=\"#django.template.backends.jinja2.Jinja2\" title=\"django.template.backends.jinja2.Jinja2\"><code class=\"xref py py-class docutils literal notranslate\">django.template.backends.jinja2.Jinja2</code></a>.</p>\n<p>Since most engines load templates from files, the top-level configuration for\neach engine contains two common settings:</p>\n<ul class=\"simple\">\n<li><p><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-DIRS\"><code class=\"xref std std-setting docutils literal notranslate\">DIRS</code></a> defines a list of directories where the\nengine should look for template source files, in search order.</p></li>\n<li><p><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-APP_DIRS\"><code class=\"xref std std-setting docutils literal notranslate\">APP_DIRS</code></a> tells whether the engine should\nlook for templates inside installed applications. Each backend defines a\nconventional name for the subdirectory inside applications where its\ntemplates should be stored.</p></li>\n</ul>\n<p>While uncommon, it's possible to configure several instances of the same\nbackend with different options. In that case you should define a unique\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-NAME\"><code class=\"xref std std-setting docutils literal notranslate\">NAME</code></a> for each engine.</p>\n<p><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-OPTIONS\"><code class=\"xref std std-setting docutils literal notranslate\">OPTIONS</code></a> contains backend-specific settings.</p>\n</section>\n<section id=\"usage\">\n<h3>Usage<a class=\"heading-anchor\" href=\"#usage\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p id=\"module-django.template.loader\"><span id=\"template-loading\"></span>The <code class=\"docutils literal notranslate\">django.template.loader</code> module defines two functions to load templates.</p>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.template.loader.get_template\">\n<span class=\"sig-name descname\">get_template</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">template_name</em>, <em class=\"sig-param\">using<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.template.loader.get_template\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>This function loads the template with the given name and returns a\n<code class=\"docutils literal notranslate\">Template</code> object.</p>\n<p>The exact type of the return value depends on the backend that loaded the\ntemplate. Each backend has its own <code class=\"docutils literal notranslate\">Template</code> class.</p>\n<p><code class=\"docutils literal notranslate\">get_template()</code> tries each template engine in order until one succeeds.\nIf the template cannot be found, it raises\n<a class=\"reference internal\" href=\"#django.template.TemplateDoesNotExist\" title=\"django.template.TemplateDoesNotExist\"><code class=\"xref py py-exc docutils literal notranslate\">TemplateDoesNotExist</code></a>. If the template is found but\ncontains invalid syntax, it raises\n<a class=\"reference internal\" href=\"#django.template.TemplateSyntaxError\" title=\"django.template.TemplateSyntaxError\"><code class=\"xref py py-exc docutils literal notranslate\">TemplateSyntaxError</code></a>.</p>\n<p>How templates are searched and loaded depends on each engine's backend and\nconfiguration.</p>\n<p>If you want to restrict the search to a particular template engine, pass\nthe engine's <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-NAME\"><code class=\"xref std std-setting docutils literal notranslate\">NAME</code></a> in the <code class=\"docutils literal notranslate\">using</code> argument.</p>\n</dd></dl>\n\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.template.loader.select_template\">\n<span class=\"sig-name descname\">select_template</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">template_name_list</em>, <em class=\"sig-param\">using<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.template.loader.select_template\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p><code class=\"docutils literal notranslate\">select_template()</code> is just like <code class=\"docutils literal notranslate\">get_template()</code>, except it takes a\nlist of template names. It tries each name in order and returns the first\ntemplate that exists.</p>\n</dd></dl>\n\n<p>If loading a template fails, the following two exceptions, defined in\n<code class=\"docutils literal notranslate\">django.template</code>, may be raised:</p>\n<dl class=\"py exception\">\n<dt class=\"sig sig-object py\" id=\"django.template.TemplateDoesNotExist\">\n<em class=\"property\"><span class=\"k\">exception</span> </em><span class=\"sig-name descname\">TemplateDoesNotExist</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">msg</em>, <em class=\"sig-param\">tried<span class=\"o\">=</span><span class=\"default_value\">None</span></em>, <em class=\"sig-param\">backend<span class=\"o\">=</span><span class=\"default_value\">None</span></em>, <em class=\"sig-param\">chain<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.template.TemplateDoesNotExist\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>This exception is raised when a template cannot be found. It accepts the\nfollowing optional arguments for populating the <a class=\"reference internal\" href=\"#template-postmortem\"><span class=\"std std-ref\">template postmortem</span></a> on the debug page:</p>\n<dl class=\"simple\">\n<dt><code class=\"docutils literal notranslate\">backend</code></dt><dd><p>The template backend instance from which the exception originated.</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\">tried</code></dt><dd><p>A list of sources that were tried when finding the template. This is\nformatted as a list of tuples containing <code class=\"docutils literal notranslate\">(origin, status)</code>, where\n<code class=\"docutils literal notranslate\">origin</code> is an <a class=\"reference internal\" href=\"#template-origin-api\"><span class=\"std std-ref\">origin-like</span></a> object and\n<code class=\"docutils literal notranslate\">status</code> is a string with the reason the template wasn't found.</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\">chain</code></dt><dd><p>A list of intermediate <a class=\"reference internal\" href=\"#django.template.TemplateDoesNotExist\" title=\"django.template.TemplateDoesNotExist\"><code class=\"xref py py-exc docutils literal notranslate\">TemplateDoesNotExist</code></a>\nexceptions raised when trying to load a template. This is used by\nfunctions, such as <a class=\"reference internal\" href=\"#django.template.loader.get_template\" title=\"django.template.loader.get_template\"><code class=\"xref py py-func docutils literal notranslate\">get_template()</code></a>, that\ntry to load a given template from multiple engines.</p>\n</dd>\n</dl>\n</dd></dl>\n\n<dl class=\"py exception\">\n<dt class=\"sig sig-object py\" id=\"django.template.TemplateSyntaxError\">\n<em class=\"property\"><span class=\"k\">exception</span> </em><span class=\"sig-name descname\">TemplateSyntaxError</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">msg</em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.template.TemplateSyntaxError\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>This exception is raised when a template was found but contains errors.</p>\n</dd></dl>\n\n<p><code class=\"docutils literal notranslate\">Template</code> objects returned by <code class=\"docutils literal notranslate\">get_template()</code> and <code class=\"docutils literal notranslate\">select_template()</code>\nmust provide a <code class=\"docutils literal notranslate\">render()</code> method with the following signature:</p>\n<dl class=\"py method\">\n<dt class=\"sig sig-object py\" id=\"django.template.backends.base.Template.render\">\n<span class=\"sig-prename descclassname\">Template.</span><span class=\"sig-name descname\">render</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">context<span class=\"o\">=</span><span class=\"default_value\">None</span></em>, <em class=\"sig-param\">request<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.template.backends.base.Template.render\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>Renders this template with a given context.</p>\n<p>If <code class=\"docutils literal notranslate\">context</code> is provided, it must be a <a class=\"reference external\" href=\"https://docs.python.org/3/library/stdtypes.html#dict\" title=\"(in Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\">dict</code></a>. If it isn't\nprovided, the engine will render the template with an empty context.</p>\n<p>If <code class=\"docutils literal notranslate\">request</code> is provided, it must be an <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/request-response/#django.http.HttpRequest\" title=\"django.http.HttpRequest\"><code class=\"xref py py-class docutils literal notranslate\">HttpRequest</code></a>.\nThen the engine must make it, as well as the CSRF token, available in the\ntemplate. How this is achieved is up to each backend.</p>\n</dd></dl>\n\n<p>Here's an example of the search algorithm. For this example the\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES\"><code class=\"xref std std-setting docutils literal notranslate\">TEMPLATES</code></a> setting is:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>TEMPLATES <span class=\"o\">=</span> <span class=\"p\">[</span>\n    <span class=\"p\">{</span>\n        <span class=\"s1\">&#39;BACKEND&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;django.template.backends.django.DjangoTemplates&#39;</span><span class=\"p\">,</span>\n        <span class=\"s1\">&#39;DIRS&#39;</span><span class=\"p\">:</span> <span class=\"p\">[</span>\n            <span class=\"s1\">&#39;/home/html/example.com&#39;</span><span class=\"p\">,</span>\n            <span class=\"s1\">&#39;/home/html/default&#39;</span><span class=\"p\">,</span>\n        <span class=\"p\">],</span>\n    <span class=\"p\">},</span>\n    <span class=\"p\">{</span>\n        <span class=\"s1\">&#39;BACKEND&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;django.template.backends.jinja2.Jinja2&#39;</span><span class=\"p\">,</span>\n        <span class=\"s1\">&#39;DIRS&#39;</span><span class=\"p\">:</span> <span class=\"p\">[</span>\n            <span class=\"s1\">&#39;/home/html/jinja2&#39;</span><span class=\"p\">,</span>\n        <span class=\"p\">],</span>\n    <span class=\"p\">},</span>\n<span class=\"p\">]</span>\n</code></pre></div>\n<p>If you call <code class=\"docutils literal notranslate\">get_template('story_detail.html')</code>, here are the files Django\nwill look for, in order:</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\">/home/html/example.com/story_detail.html</code> (<code class=\"docutils literal notranslate\">'django'</code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\">/home/html/default/story_detail.html</code> (<code class=\"docutils literal notranslate\">'django'</code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\">/home/html/jinja2/story_detail.html</code> (<code class=\"docutils literal notranslate\">'jinja2'</code> engine)</p></li>\n</ul>\n<p>If you call <code class=\"docutils literal notranslate\">select_template(['story_253_detail.html', 'story_detail.html'])</code>,\nhere's what Django will look for:</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\">/home/html/example.com/story_253_detail.html</code> (<code class=\"docutils literal notranslate\">'django'</code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\">/home/html/default/story_253_detail.html</code> (<code class=\"docutils literal notranslate\">'django'</code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\">/home/html/jinja2/story_253_detail.html</code> (<code class=\"docutils literal notranslate\">'jinja2'</code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\">/home/html/example.com/story_detail.html</code> (<code class=\"docutils literal notranslate\">'django'</code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\">/home/html/default/story_detail.html</code> (<code class=\"docutils literal notranslate\">'django'</code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\">/home/html/jinja2/story_detail.html</code> (<code class=\"docutils literal notranslate\">'jinja2'</code> engine)</p></li>\n</ul>\n<p>When Django finds a template that exists, it stops looking.</p>\n<aside class=\"admonition-tip admonition\" role=\"note\">\n<p class=\"admonition-title\">Tip</p>\n<p>You can use <a class=\"reference internal\" href=\"#django.template.loader.select_template\" title=\"django.template.loader.select_template\"><code class=\"xref py py-func docutils literal notranslate\">select_template()</code></a> for flexible\ntemplate loading. For example, if you've written a news story and want\nsome stories to have custom templates, use something like\n<code class=\"docutils literal notranslate\">select_template(['story_%s_detail.html' % story.id,\n'story_detail.html'])</code>. That'll allow you to use a custom template for an\nindividual story, with a fallback template for stories that don't have\ncustom templates.</p>\n</aside>\n<p>It's possible -- and preferable -- to organize templates in subdirectories\ninside each directory containing templates. The convention is to make a\nsubdirectory for each Django app, with subdirectories within those\nsubdirectories as needed.</p>\n<p>Do this for your own sanity. Storing all templates in the root level of a\nsingle directory gets messy.</p>\n<p>To load a template that's within a subdirectory, just use a slash, like so:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>get_template<span class=\"p\">(</span><span class=\"s1\">&#39;news/story_detail.html&#39;</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>Using the same <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES\"><code class=\"xref std std-setting docutils literal notranslate\">TEMPLATES</code></a> option as above, this will attempt to load\nthe following templates:</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\">/home/html/example.com/news/story_detail.html</code> (<code class=\"docutils literal notranslate\">'django'</code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\">/home/html/default/news/story_detail.html</code> (<code class=\"docutils literal notranslate\">'django'</code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\">/home/html/jinja2/news/story_detail.html</code> (<code class=\"docutils literal notranslate\">'jinja2'</code> engine)</p></li>\n</ul>\n<p>此外，为了减少加载和渲染模板的重复性，Django 提供了一个自动处理的快捷函数。</p>\n<dl class=\"py function\">\n<dt class=\"sig sig-object py\" id=\"django.template.loader.render_to_string\">\n<span class=\"sig-name descname\">render_to_string</span><span class=\"sig-paren\">(</span><em class=\"sig-param\">template_name</em>, <em class=\"sig-param\">context<span class=\"o\">=</span><span class=\"default_value\">None</span></em>, <em class=\"sig-param\">request<span class=\"o\">=</span><span class=\"default_value\">None</span></em>, <em class=\"sig-param\">using<span class=\"o\">=</span><span class=\"default_value\">None</span></em><span class=\"sig-paren\">)</span><a class=\"heading-anchor\" href=\"#django.template.loader.render_to_string\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p><code class=\"docutils literal notranslate\">render_to_string()</code> 加载一个模板 <a class=\"reference internal\" href=\"#django.template.loader.get_template\" title=\"django.template.loader.get_template\"><code class=\"xref py py-func docutils literal notranslate\">get_template()</code></a> ，并立即调用它的 <code class=\"docutils literal notranslate\">render()</code> 方法。它需要下面的参数。</p>\n<dl class=\"simple\">\n<dt><code class=\"docutils literal notranslate\">template_name</code></dt><dd><p>加载和呈现模板的名称。如果是模板名称列表，Django 使用 <a class=\"reference internal\" href=\"#django.template.loader.select_template\" title=\"django.template.loader.select_template\"><code class=\"xref py py-func docutils literal notranslate\">select_template()</code></a> ，而不是 <a class=\"reference internal\" href=\"#django.template.loader.get_template\" title=\"django.template.loader.get_template\"><code class=\"xref py py-func docutils literal notranslate\">get_template()</code></a> 找到模板。</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\">context</code></dt><dd><p> <a class=\"reference external\" href=\"https://docs.python.org/3/library/stdtypes.html#dict\" title=\"(in Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\">dict</code></a> 用作模板的渲染上下文。</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\">request</code></dt><dd><p> 可选项 <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/request-response/#django.http.HttpRequest\" title=\"django.http.HttpRequest\"><code class=\"xref py py-class docutils literal notranslate\">HttpRequest</code></a> 在模板的渲染过程中可用。</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\">using</code></dt><dd><p>可选的模板引擎 <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-NAME\"><code class=\"xref std std-setting docutils literal notranslate\">NAME</code></a>。对模板的搜索将限于该引擎。</p>\n</dd>\n</dl>\n<p>使用实例：</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.template.loader</span> <span class=\"kn\">import</span> render_to_string\nrendered <span class=\"o\">=</span> render_to_string<span class=\"p\">(</span><span class=\"s1\">&#39;my_template.html&#39;</span><span class=\"p\">,</span> <span class=\"p\">{</span><span class=\"s1\">&#39;foo&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;bar&#39;</span><span class=\"p\">})</span>\n</code></pre></div>\n</dd></dl>\n\n<p>还可以参看 <a class=\"reference internal\" href=\"/zh-hans/2.0/topics/http/shortcuts/#django.shortcuts.render\" title=\"django.shortcuts.render\"><code class=\"xref py py-func docutils literal notranslate\">render()</code></a> 快捷函数，它调用 <a class=\"reference internal\" href=\"#django.template.loader.render_to_string\" title=\"django.template.loader.render_to_string\"><code class=\"xref py py-func docutils literal notranslate\">render_to_string()</code></a> ，并将结果提供给 <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/request-response/#django.http.HttpResponse\" title=\"django.http.HttpResponse\"><code class=\"xref py py-class docutils literal notranslate\">HttpResponse</code></a> ，适合从视图返回。</p>\n<p>最后，您可以直接使用配置好的引擎：</p>\n<dl class=\"py data\">\n<dt class=\"sig sig-object py\" id=\"django.template.loader.engines\">\n<span class=\"sig-name descname\">engines</span><a class=\"heading-anchor\" href=\"#django.template.loader.engines\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd><p>模板引擎可在 <code class=\"docutils literal notranslate\">django.template.engines</code> 中使用：</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.template</span> <span class=\"kn\">import</span> engines\n\ndjango_engine <span class=\"o\">=</span> engines<span class=\"p\">[</span><span class=\"s1\">&#39;django&#39;</span><span class=\"p\">]</span>\ntemplate <span class=\"o\">=</span> django_engine<span class=\"o\">.</span>from_string<span class=\"p\">(</span><span class=\"s2\">&quot;Hello {{ name }}!&quot;</span><span class=\"p\">)</span>\n</code></pre></div>\n<p>在这个例子中，查找关键字“django”是引擎的 <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-NAME\"><code class=\"xref std std-setting docutils literal notranslate\">NAME</code></a>。</p>\n</dd></dl>\n\n</section>\n<section id=\"module-django.template.backends.django\">\n<span id=\"built-in-backends\"></span><span id=\"module-django.template.backends\"></span><h3>内置后端<a class=\"heading-anchor\" href=\"#module-django.template.backends.django\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<dl class=\"py class\">\n<dt class=\"sig sig-object py\" id=\"django.template.backends.django.DjangoTemplates\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">DjangoTemplates</span><a class=\"heading-anchor\" href=\"#django.template.backends.django.DjangoTemplates\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>设置 <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-BACKEND\"><code class=\"xref std std-setting docutils literal notranslate\">BACKEND</code></a> 为 <code class=\"docutils literal notranslate\">'django.template.backends.django.DjangoTemplates'</code>，以配置 Django 模板引擎。</p>\n<p>When <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-APP_DIRS\"><code class=\"xref std std-setting docutils literal notranslate\">APP_DIRS</code></a> is <code class=\"docutils literal notranslate\">True</code>, <code class=\"docutils literal notranslate\">DjangoTemplates</code>\nengines look for templates in the <code class=\"docutils literal notranslate\">templates</code> subdirectory of installed\napplications. This generic name was kept for backwards-compatibility.</p>\n<p><code class=\"docutils literal notranslate\">DjangoTemplates</code> engines accept the following <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-OPTIONS\"><code class=\"xref std std-setting docutils literal notranslate\">OPTIONS</code></a>:</p>\n<ul>\n<li><p><code class=\"docutils literal notranslate\">'autoescape'</code>: a boolean that controls whether HTML autoescaping is\nenabled.</p>\n<p>It defaults to <code class=\"docutils literal notranslate\">True</code>.</p>\n<aside class=\"admonition admonition-warning\" role=\"note\">\n<p class=\"admonition-title\">Warning</p>\n<p>Only set it to <code class=\"docutils literal notranslate\">False</code> if you're rendering non-HTML templates!</p>\n</aside>\n</li>\n<li><p><code class=\"docutils literal notranslate\">'context_processors'</code>: a list of dotted Python paths to callables that\nare used to populate the context when a template is rendered with a request.\nThese callables take a request object as their argument and return a\n<a class=\"reference external\" href=\"https://docs.python.org/3/library/stdtypes.html#dict\" title=\"(in Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\">dict</code></a> of items to be merged into the context.</p>\n<p>It defaults to an empty list.</p>\n<p>See <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#django.template.RequestContext\" title=\"django.template.RequestContext\"><code class=\"xref py py-class docutils literal notranslate\">RequestContext</code></a> for more information.</p>\n</li>\n<li><p><code class=\"docutils literal notranslate\">'debug'</code>: a boolean that turns on/off template debug mode. If it is\n<code class=\"docutils literal notranslate\">True</code>, the fancy error page will display a detailed report for any\nexception raised during template rendering. This report contains the\nrelevant snippet of the template with the appropriate line highlighted.</p>\n<p>It defaults to the value of the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-DEBUG\"><code class=\"xref std std-setting docutils literal notranslate\">DEBUG</code></a> setting.</p>\n</li>\n<li><p><code class=\"docutils literal notranslate\">'loaders'</code>: a list of dotted Python paths to template loader classes.\nEach <code class=\"docutils literal notranslate\">Loader</code> class knows how to import templates from a particular\nsource. Optionally, a tuple can be used instead of a string. The first item\nin the tuple should be the <code class=\"docutils literal notranslate\">Loader</code> class name, and subsequent items are\npassed to the <code class=\"docutils literal notranslate\">Loader</code> during initialization.</p>\n<p>The default depends on the values of <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-DIRS\"><code class=\"xref std std-setting docutils literal notranslate\">DIRS</code></a> and\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-APP_DIRS\"><code class=\"xref std std-setting docutils literal notranslate\">APP_DIRS</code></a>.</p>\n<p>See <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#template-loaders\"><span class=\"std std-ref\">Loader types</span></a> for details.</p>\n</li>\n<li><p><code class=\"docutils literal notranslate\">'string_if_invalid'</code>: the output, as a string, that the template system\nshould use for invalid (e.g. misspelled) variables.</p>\n<p>It defaults to an empty string.</p>\n<p>See <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#invalid-template-variables\"><span class=\"std std-ref\">How invalid variables are handled</span></a> for details.</p>\n</li>\n<li><p><code class=\"docutils literal notranslate\">'file_charset'</code>: the charset used to read template files on disk.</p>\n<p>It defaults to the value of <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-FILE_CHARSET\"><code class=\"xref std std-setting docutils literal notranslate\">FILE_CHARSET</code></a>.</p>\n</li>\n<li><p><code class=\"docutils literal notranslate\">'libraries'</code>: A dictionary of labels and dotted Python paths of template\ntag modules to register with the template engine. This can be used to add\nnew libraries or provide alternate labels for existing ones. For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>OPTIONS<span class=\"o\">=</span><span class=\"p\">{</span>\n    <span class=\"s1\">&#39;libraries&#39;</span><span class=\"p\">:</span> <span class=\"p\">{</span>\n        <span class=\"s1\">&#39;myapp_tags&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;path.to.myapp.tags&#39;</span><span class=\"p\">,</span>\n        <span class=\"s1\">&#39;admin.urls&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;django.contrib.admin.templatetags.admin_urls&#39;</span><span class=\"p\">,</span>\n    <span class=\"p\">},</span>\n<span class=\"p\">}</span>\n</code></pre></div>\n<p>Libraries can be loaded by passing the corresponding dictionary key to\nthe <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/builtins/#std-templatetag-load\"><code class=\"xref std std-ttag docutils literal notranslate\">{% load %}</code></a> tag.</p>\n</li>\n<li><p><code class=\"docutils literal notranslate\">'builtins'</code>: A list of dotted Python paths of template tag modules to\nadd to <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/builtins/\"><span class=\"doc\">built-ins</span></a>. For example:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code>OPTIONS<span class=\"o\">=</span><span class=\"p\">{</span>\n    <span class=\"s1\">&#39;builtins&#39;</span><span class=\"p\">:</span> <span class=\"p\">[</span><span class=\"s1\">&#39;myapp.builtins&#39;</span><span class=\"p\">],</span>\n<span class=\"p\">}</span>\n</code></pre></div>\n<p>Tags and filters from built-in libraries can be used without first calling\nthe <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/builtins/#std-templatetag-load\"><code class=\"xref std std-ttag docutils literal notranslate\">{% load %}</code></a> tag.</p>\n</li>\n</ul>\n<dl class=\"py class\" id=\"module-django.template.backends.jinja2\">\n<dt class=\"sig sig-object py\" id=\"django.template.backends.jinja2.Jinja2\">\n<em class=\"property\"><span class=\"k\">class</span> </em><span class=\"sig-name descname\">Jinja2</span><a class=\"heading-anchor\" href=\"#django.template.backends.jinja2.Jinja2\"><span class=\"visually-hidden\">Link to this definition</span><span aria-hidden=\"true\">#</span></a></dt>\n<dd></dd></dl>\n\n<p>Requires <a class=\"reference external\" href=\"http://jinja.pocoo.org/\">Jinja2</a> to be installed:</p>\n<div class=\"code-block\" data-language=\"console\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Shell</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Shell code\"><code><span class=\"gp\">$ </span>pip install Jinja2\n</code></pre></div>\n<p>Set <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-BACKEND\"><code class=\"xref std std-setting docutils literal notranslate\">BACKEND</code></a> to\n<code class=\"docutils literal notranslate\">'django.template.backends.jinja2.Jinja2'</code> to configure a <a class=\"reference external\" href=\"http://jinja.pocoo.org/\">Jinja2</a> engine.</p>\n<p>When <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-APP_DIRS\"><code class=\"xref std std-setting docutils literal notranslate\">APP_DIRS</code></a> is <code class=\"docutils literal notranslate\">True</code>, <code class=\"docutils literal notranslate\">Jinja2</code> engines\nlook for templates in the <code class=\"docutils literal notranslate\">jinja2</code> subdirectory of installed applications.</p>\n<p>The most important entry in <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-OPTIONS\"><code class=\"xref std std-setting docutils literal notranslate\">OPTIONS</code></a> is\n<code class=\"docutils literal notranslate\">'environment'</code>. It's a dotted Python path to a callable returning a Jinja2\nenvironment. It defaults to <code class=\"docutils literal notranslate\">'jinja2.Environment'</code>. Django invokes that\ncallable and passes other options as keyword arguments. Furthermore, Django\nadds defaults that differ from Jinja2's for a few options:</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\">'autoescape'</code>: <code class=\"docutils literal notranslate\">True</code></p></li>\n<li><p><code class=\"docutils literal notranslate\">'loader'</code>: a loader configured for <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-DIRS\"><code class=\"xref std std-setting docutils literal notranslate\">DIRS</code></a> and\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-APP_DIRS\"><code class=\"xref std std-setting docutils literal notranslate\">APP_DIRS</code></a></p></li>\n<li><p><code class=\"docutils literal notranslate\">'auto_reload'</code>: <code class=\"docutils literal notranslate\">settings.DEBUG</code></p></li>\n<li><p><code class=\"docutils literal notranslate\">'undefined'</code>: <code class=\"docutils literal notranslate\">DebugUndefined if settings.DEBUG else Undefined</code></p></li>\n</ul>\n<p><code class=\"docutils literal notranslate\">Jinja2</code> engines also accept the following <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/settings/#std-setting-TEMPLATES-OPTIONS\"><code class=\"xref std std-setting docutils literal notranslate\">OPTIONS</code></a>:</p>\n<ul>\n<li><p><code class=\"docutils literal notranslate\">'context_processors'</code>: a list of dotted Python paths to callables that\nare used to populate the context when a template is rendered with a request.\nThese callables take a request object as their argument and return a\n<a class=\"reference external\" href=\"https://docs.python.org/3/library/stdtypes.html#dict\" title=\"(in Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\">dict</code></a> of items to be merged into the context.</p>\n<p>It defaults to an empty list.</p>\n<aside class=\"admonition-using-context-processors-with-jinja2-templates-is-discouraged admonition\" role=\"note\">\n<p class=\"admonition-title\">Using context processors with Jinja2 templates is discouraged.</p>\n<p>Context processors are useful with Django templates because Django templates\ndon't support calling functions with arguments. Since Jinja2 doesn't have\nthat limitation, it's recommended to put the function that you would use as a\ncontext processor in the global variables available to the template using\n<code class=\"docutils literal notranslate\">jinja2.Environment</code> as described below. You can then call that function in\nthe template:</p>\n<div class=\"code-block\" data-language=\"jinja\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Jinja</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Jinja code\"><code><span class=\"cp\">{{</span> <span class=\"nv\">function</span><span class=\"o\">(</span><span class=\"nv\">request</span><span class=\"o\">)</span> <span class=\"cp\">}}</span>\n</code></pre></div>\n<p>Some Django templates context processors return a fixed value. For Jinja2\ntemplates, this layer of indirection isn't necessary since you can add\nconstants directly in <code class=\"docutils literal notranslate\">jinja2.Environment</code>.</p>\n<p>The original use case for adding context processors for Jinja2 involved:</p>\n<ul class=\"simple\">\n<li><p>Making an expensive computation that depends on the request.</p></li>\n<li><p>Needing the result in every template.</p></li>\n<li><p>Using the result multiple times in each template.</p></li>\n</ul>\n<p>Unless all of these conditions are met, passing a function to the template is\nsimpler and more in line with the design of Jinja2.</p>\n</aside>\n</li>\n</ul>\n<aside class=\"version-note version-added\" data-version=\"1.11\" role=\"note\">\n<p class=\"version-note-title\">New in Django 1.11</p><p>The <code class=\"docutils literal notranslate\">'context_processors'</code> option was added.</p>\n</aside>\n<p>The default configuration is purposefully kept to a minimum. If a template is\nrendered with a request (e.g. when using <a class=\"reference internal\" href=\"/zh-hans/2.0/topics/http/shortcuts/#django.shortcuts.render\" title=\"django.shortcuts.render\"><code class=\"xref py py-func docutils literal notranslate\">render()</code></a>),\nthe <code class=\"docutils literal notranslate\">Jinja2</code> backend adds the globals <code class=\"docutils literal notranslate\">request</code>, <code class=\"docutils literal notranslate\">csrf_input</code>, and\n<code class=\"docutils literal notranslate\">csrf_token</code> to the context. Apart from that, this backend doesn't create a\nDjango-flavored environment. It doesn't know about Django filters and tags.\nIn order to use Django-specific APIs, you must configure them into the\nenvironment.</p>\n<p>For example, you can create <code class=\"docutils literal notranslate\">myproject/jinja2.py</code> with this content:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.contrib.staticfiles.storage</span> <span class=\"kn\">import</span> staticfiles_storage\n<span class=\"kn\">from</span> <span class=\"nn\">django.urls</span> <span class=\"kn\">import</span> reverse\n\n<span class=\"kn\">from</span> <span class=\"nn\">jinja2</span> <span class=\"kn\">import</span> Environment\n\n\n<span class=\"k\">def</span> <span class=\"nf\">environment</span><span class=\"p\">(</span><span class=\"o\">**</span>options<span class=\"p\">):</span>\n    env <span class=\"o\">=</span> Environment<span class=\"p\">(</span><span class=\"o\">**</span>options<span class=\"p\">)</span>\n    env<span class=\"o\">.</span>globals<span class=\"o\">.</span>update<span class=\"p\">({</span>\n        <span class=\"s1\">&#39;static&#39;</span><span class=\"p\">:</span> staticfiles_storage<span class=\"o\">.</span>url<span class=\"p\">,</span>\n        <span class=\"s1\">&#39;url&#39;</span><span class=\"p\">:</span> reverse<span class=\"p\">,</span>\n    <span class=\"p\">})</span>\n    <span class=\"k\">return</span> env\n</code></pre></div>\n<p>and set the <code class=\"docutils literal notranslate\">'environment'</code> option to <code class=\"docutils literal notranslate\">'myproject.jinja2.environment'</code>.</p>\n<p>Then you could use the following constructs in Jinja2 templates:</p>\n<div class=\"code-block\" data-language=\"html+jinja\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Html Jinja</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Html Jinja code\"><code><span class=\"p\">&lt;</span><span class=\"nt\">img</span> <span class=\"na\">src</span><span class=\"o\">=</span><span class=\"s\">&quot;</span><span class=\"cp\">{{</span> <span class=\"nv\">static</span><span class=\"o\">(</span><span class=\"s1\">&#39;path/to/company-logo.png&#39;</span><span class=\"o\">)</span> <span class=\"cp\">}}</span><span class=\"s\">&quot;</span> <span class=\"na\">alt</span><span class=\"o\">=</span><span class=\"s\">&quot;Company Logo&quot;</span><span class=\"p\">&gt;</span>\n\n<span class=\"p\">&lt;</span><span class=\"nt\">a</span> <span class=\"na\">href</span><span class=\"o\">=</span><span class=\"s\">&quot;</span><span class=\"cp\">{{</span> <span class=\"nv\">url</span><span class=\"o\">(</span><span class=\"s1\">&#39;admin:index&#39;</span><span class=\"o\">)</span> <span class=\"cp\">}}</span><span class=\"s\">&quot;</span><span class=\"p\">&gt;</span>Administration<span class=\"p\">&lt;/</span><span class=\"nt\">a</span><span class=\"p\">&gt;</span>\n</code></pre></div>\n<p>The concepts of tags and filters exist both in the Django template language\nand in Jinja2 but they're used differently. Since Jinja2 supports passing\narguments to callables in templates, many features that require a template tag\nor filter in Django templates can be achieved simply by calling a function in\nJinja2 templates, as shown in the example above. Jinja2's global namespace\nremoves the need for template context processors. The Django template language\ndoesn't have an equivalent of Jinja2 tests.</p>\n</section>\n<section id=\"custom-backends\">\n<h3>Custom backends<a class=\"heading-anchor\" href=\"#custom-backends\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>Here's how to implement a custom template backend in order to use another\ntemplate system. A template backend is a class that inherits\n<code class=\"docutils literal notranslate\">django.template.backends.base.BaseEngine</code>. It must implement\n<code class=\"docutils literal notranslate\">get_template()</code> and optionally <code class=\"docutils literal notranslate\">from_string()</code>. Here's an example for a\nfictional <code class=\"docutils literal notranslate\">foobar</code> template library:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"kn\">from</span> <span class=\"nn\">django.template</span> <span class=\"kn\">import</span> TemplateDoesNotExist<span class=\"p\">,</span> TemplateSyntaxError\n<span class=\"kn\">from</span> <span class=\"nn\">django.template.backends.base</span> <span class=\"kn\">import</span> BaseEngine\n<span class=\"kn\">from</span> <span class=\"nn\">django.template.backends.utils</span> <span class=\"kn\">import</span> csrf_input_lazy<span class=\"p\">,</span> csrf_token_lazy\n\n<span class=\"kn\">import</span> <span class=\"nn\">foobar</span>\n\n\n<span class=\"k\">class</span> <span class=\"nc\">FooBar</span><span class=\"p\">(</span>BaseEngine<span class=\"p\">):</span>\n\n    <span class=\"c1\"># Name of the subdirectory containing the templates for this engine</span>\n    <span class=\"c1\"># inside an installed application.</span>\n    app_dirname <span class=\"o\">=</span> <span class=\"s1\">&#39;foobar&#39;</span>\n\n    <span class=\"k\">def</span> <span class=\"fm\">__init__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> params<span class=\"p\">):</span>\n        params <span class=\"o\">=</span> params<span class=\"o\">.</span>copy<span class=\"p\">()</span>\n        options <span class=\"o\">=</span> params<span class=\"o\">.</span>pop<span class=\"p\">(</span><span class=\"s1\">&#39;OPTIONS&#39;</span><span class=\"p\">)</span><span class=\"o\">.</span>copy<span class=\"p\">()</span>\n        <span class=\"nb\">super</span><span class=\"p\">()</span><span class=\"o\">.</span><span class=\"fm\">__init__</span><span class=\"p\">(</span>params<span class=\"p\">)</span>\n\n        <span class=\"bp\">self</span><span class=\"o\">.</span>engine <span class=\"o\">=</span> foobar<span class=\"o\">.</span>Engine<span class=\"p\">(</span><span class=\"o\">**</span>options<span class=\"p\">)</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">from_string</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> template_code<span class=\"p\">):</span>\n        <span class=\"k\">try</span><span class=\"p\">:</span>\n          <span class=\"k\">return</span> Template<span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span>engine<span class=\"o\">.</span>from_string<span class=\"p\">(</span>template_code<span class=\"p\">))</span>\n        <span class=\"k\">except</span> foobar<span class=\"o\">.</span>TemplateCompilationFailed <span class=\"k\">as</span> exc<span class=\"p\">:</span>\n            <span class=\"k\">raise</span> TemplateSyntaxError<span class=\"p\">(</span>exc<span class=\"o\">.</span>args<span class=\"p\">)</span>\n\n    <span class=\"k\">def</span> <span class=\"nf\">get_template</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> template_name<span class=\"p\">):</span>\n        <span class=\"k\">try</span><span class=\"p\">:</span>\n            <span class=\"k\">return</span> Template<span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span>engine<span class=\"o\">.</span>get_template<span class=\"p\">(</span>template_name<span class=\"p\">))</span>\n        <span class=\"k\">except</span> foobar<span class=\"o\">.</span>TemplateNotFound <span class=\"k\">as</span> exc<span class=\"p\">:</span>\n            <span class=\"k\">raise</span> TemplateDoesNotExist<span class=\"p\">(</span>exc<span class=\"o\">.</span>args<span class=\"p\">,</span> backend<span class=\"o\">=</span><span class=\"bp\">self</span><span class=\"p\">)</span>\n        <span class=\"k\">except</span> foobar<span class=\"o\">.</span>TemplateCompilationFailed <span class=\"k\">as</span> exc<span class=\"p\">:</span>\n            <span class=\"k\">raise</span> TemplateSyntaxError<span class=\"p\">(</span>exc<span class=\"o\">.</span>args<span class=\"p\">)</span>\n\n\n<span class=\"k\">class</span> <span class=\"nc\">Template</span><span class=\"p\">:</span>\n\n    <span class=\"k\">def</span> <span class=\"fm\">__init__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> template<span class=\"p\">):</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span>template <span class=\"o\">=</span> template\n\n    <span class=\"k\">def</span> <span class=\"nf\">render</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> context<span class=\"o\">=</span><span class=\"kc\">None</span><span class=\"p\">,</span> request<span class=\"o\">=</span><span class=\"kc\">None</span><span class=\"p\">):</span>\n        <span class=\"k\">if</span> context <span class=\"ow\">is</span> <span class=\"kc\">None</span><span class=\"p\">:</span>\n            context <span class=\"o\">=</span> <span class=\"p\">{}</span>\n        <span class=\"k\">if</span> request <span class=\"ow\">is</span> <span class=\"ow\">not</span> <span class=\"kc\">None</span><span class=\"p\">:</span>\n            context<span class=\"p\">[</span><span class=\"s1\">&#39;request&#39;</span><span class=\"p\">]</span> <span class=\"o\">=</span> request\n            context<span class=\"p\">[</span><span class=\"s1\">&#39;csrf_input&#39;</span><span class=\"p\">]</span> <span class=\"o\">=</span> csrf_input_lazy<span class=\"p\">(</span>request<span class=\"p\">)</span>\n            context<span class=\"p\">[</span><span class=\"s1\">&#39;csrf_token&#39;</span><span class=\"p\">]</span> <span class=\"o\">=</span> csrf_token_lazy<span class=\"p\">(</span>request<span class=\"p\">)</span>\n        <span class=\"k\">return</span> <span class=\"bp\">self</span><span class=\"o\">.</span>template<span class=\"o\">.</span>render<span class=\"p\">(</span>context<span class=\"p\">)</span>\n</code></pre></div>\n<p>See <a class=\"reference external\" href=\"https://github.com/django/deps/blob/master/final/0182-multiple-template-engines.rst\">DEP 182</a> for more information.</p>\n</section>\n<section id=\"debug-integration-for-custom-engines\">\n<span id=\"template-debug-integration\"></span><h3>Debug integration for custom engines<a class=\"heading-anchor\" href=\"#debug-integration-for-custom-engines\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<p>The Django debug page has hooks to provide detailed information when a template\nerror arises. Custom template engines can use these hooks to enhance the\ntraceback information that appears to users. The following hooks are available:</p>\n<section id=\"template-postmortem\">\n<span id=\"id1\"></span><h4>Template postmortem<a class=\"heading-anchor\" href=\"#template-postmortem\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>The postmortem appears when <a class=\"reference internal\" href=\"#django.template.TemplateDoesNotExist\" title=\"django.template.TemplateDoesNotExist\"><code class=\"xref py py-exc docutils literal notranslate\">TemplateDoesNotExist</code></a> is\nraised. It lists the template engines and loaders that were used when trying\nto find a given template. For example, if two Django engines are configured,\nthe postmortem will appear like:</p>\n<img alt=\"/zh-hans/2.0/_images/postmortem.png\" src=\"/zh-hans/2.0/_images/postmortem.png\" />\n<p>Custom engines can populate the postmortem by passing the <code class=\"docutils literal notranslate\">backend</code> and\n<code class=\"docutils literal notranslate\">tried</code> arguments when raising <a class=\"reference internal\" href=\"#django.template.TemplateDoesNotExist\" title=\"django.template.TemplateDoesNotExist\"><code class=\"xref py py-exc docutils literal notranslate\">TemplateDoesNotExist</code></a>.\nBackends that use the postmortem <a class=\"reference internal\" href=\"#template-origin-api\"><span class=\"std std-ref\">should specify an origin</span></a> on the template object.</p>\n</section>\n<section id=\"contextual-line-information\">\n<h4>Contextual line information<a class=\"heading-anchor\" href=\"#contextual-line-information\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>If an error happens during template parsing or rendering, Django can display\nthe line the error happened on. For example:</p>\n<img alt=\"/zh-hans/2.0/_images/template-lines.png\" src=\"/zh-hans/2.0/_images/template-lines.png\" />\n<p>Custom engines can populate this information by setting a <code class=\"docutils literal notranslate\">template_debug</code>\nattribute on exceptions raised during parsing and rendering. This attribute\nis a <a class=\"reference external\" href=\"https://docs.python.org/3/library/stdtypes.html#dict\" title=\"(in Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\">dict</code></a> with the following values:</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\">'name'</code>: The name of the template in which the exception occurred.</p></li>\n<li><p><code class=\"docutils literal notranslate\">'message'</code>: The exception message.</p></li>\n<li><p><code class=\"docutils literal notranslate\">'source_lines'</code>: The lines before, after, and including the line the\nexception occurred on. This is for context, so it shouldn't contain more than\n20 lines or so.</p></li>\n<li><p><code class=\"docutils literal notranslate\">'line'</code>: The line number on which the exception occurred.</p></li>\n<li><p><code class=\"docutils literal notranslate\">'before'</code>: The content on the error line before the token that raised the\nerror.</p></li>\n<li><p><code class=\"docutils literal notranslate\">'during'</code>: The token that raised the error.</p></li>\n<li><p><code class=\"docutils literal notranslate\">'after'</code>: The content on the error line after the token that raised the\nerror.</p></li>\n<li><p><code class=\"docutils literal notranslate\">'total'</code>: The number of lines in <code class=\"docutils literal notranslate\">source_lines</code>.</p></li>\n<li><p><code class=\"docutils literal notranslate\">'top'</code>: The line number where <code class=\"docutils literal notranslate\">source_lines</code> starts.</p></li>\n<li><p><code class=\"docutils literal notranslate\">'bottom'</code>: The line number where <code class=\"docutils literal notranslate\">source_lines</code> ends.</p></li>\n</ul>\n<p>Given the above template error, <code class=\"docutils literal notranslate\">template_debug</code> would look like:</p>\n<div class=\"code-block\" data-language=\"default\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Code</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Code code\"><code><span class=\"p\">{</span>\n    <span class=\"s1\">&#39;name&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;/path/to/template.html&#39;</span><span class=\"p\">,</span>\n    <span class=\"s1\">&#39;message&#39;</span><span class=\"p\">:</span> <span class=\"s2\">&quot;Invalid block tag: &#39;syntax&#39;&quot;</span><span class=\"p\">,</span>\n    <span class=\"s1\">&#39;source_lines&#39;</span><span class=\"p\">:</span> <span class=\"p\">[</span>\n        <span class=\"p\">(</span><span class=\"mi\">1</span><span class=\"p\">,</span> <span class=\"s1\">&#39;some</span><span class=\"se\">\\n</span><span class=\"s1\">&#39;</span><span class=\"p\">),</span>\n        <span class=\"p\">(</span><span class=\"mi\">2</span><span class=\"p\">,</span> <span class=\"s1\">&#39;lines</span><span class=\"se\">\\n</span><span class=\"s1\">&#39;</span><span class=\"p\">),</span>\n        <span class=\"p\">(</span><span class=\"mi\">3</span><span class=\"p\">,</span> <span class=\"s1\">&#39;before</span><span class=\"se\">\\n</span><span class=\"s1\">&#39;</span><span class=\"p\">),</span>\n        <span class=\"p\">(</span><span class=\"mi\">4</span><span class=\"p\">,</span> <span class=\"s1\">&#39;Hello {</span><span class=\"si\">% s</span><span class=\"s1\">yntax error %} {{ world }}</span><span class=\"se\">\\n</span><span class=\"s1\">&#39;</span><span class=\"p\">),</span>\n        <span class=\"p\">(</span><span class=\"mi\">5</span><span class=\"p\">,</span> <span class=\"s1\">&#39;some</span><span class=\"se\">\\n</span><span class=\"s1\">&#39;</span><span class=\"p\">),</span>\n        <span class=\"p\">(</span><span class=\"mi\">6</span><span class=\"p\">,</span> <span class=\"s1\">&#39;lines</span><span class=\"se\">\\n</span><span class=\"s1\">&#39;</span><span class=\"p\">),</span>\n        <span class=\"p\">(</span><span class=\"mi\">7</span><span class=\"p\">,</span> <span class=\"s1\">&#39;after</span><span class=\"se\">\\n</span><span class=\"s1\">&#39;</span><span class=\"p\">),</span>\n        <span class=\"p\">(</span><span class=\"mi\">8</span><span class=\"p\">,</span> <span class=\"s1\">&#39;&#39;</span><span class=\"p\">),</span>\n    <span class=\"p\">],</span>\n    <span class=\"s1\">&#39;line&#39;</span><span class=\"p\">:</span> <span class=\"mi\">4</span><span class=\"p\">,</span>\n    <span class=\"s1\">&#39;before&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;Hello &#39;</span><span class=\"p\">,</span>\n    <span class=\"s1\">&#39;during&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39;{</span><span class=\"si\">% s</span><span class=\"s1\">yntax error %}&#39;</span><span class=\"p\">,</span>\n    <span class=\"s1\">&#39;after&#39;</span><span class=\"p\">:</span> <span class=\"s1\">&#39; {{ world }}</span><span class=\"se\">\\n</span><span class=\"s1\">&#39;</span><span class=\"p\">,</span>\n    <span class=\"s1\">&#39;total&#39;</span><span class=\"p\">:</span> <span class=\"mi\">9</span><span class=\"p\">,</span>\n    <span class=\"s1\">&#39;bottom&#39;</span><span class=\"p\">:</span> <span class=\"mi\">9</span><span class=\"p\">,</span>\n    <span class=\"s1\">&#39;top&#39;</span><span class=\"p\">:</span> <span class=\"mi\">1</span><span class=\"p\">,</span>\n<span class=\"p\">}</span>\n</code></pre></div>\n</section>\n<section id=\"origin-api-and-3rd-party-integration\">\n<span id=\"template-origin-api\"></span><h4>Origin API and 3rd-party integration<a class=\"heading-anchor\" href=\"#origin-api-and-3rd-party-integration\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>Django templates have an <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#django.template.base.Origin\" title=\"django.template.base.Origin\"><code class=\"xref py py-class docutils literal notranslate\">Origin</code></a> object available\nthrough the <code class=\"docutils literal notranslate\">template.origin</code> attribute. This enables debug information to be\ndisplayed in the <a class=\"reference internal\" href=\"#template-postmortem\"><span class=\"std std-ref\">template postmortem</span></a>, as well as\nin 3rd-party libraries, like the <a class=\"reference external\" href=\"https://github.com/jazzband/django-debug-toolbar\">Django Debug Toolbar</a>.</p>\n<p>Custom engines can provide their own <code class=\"docutils literal notranslate\">template.origin</code> information by\ncreating an object that specifies the following attributes:</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\">'name'</code>: The full path to the template.</p></li>\n<li><p><code class=\"docutils literal notranslate\">'template_name'</code>: The relative path to the template as passed into the\nthe template loading methods.</p></li>\n<li><p><code class=\"docutils literal notranslate\">'loader_name'</code>: An optional string identifying the function or class used\nto load the template, e.g. <code class=\"docutils literal notranslate\">django.template.loaders.filesystem.Loader</code>.</p></li>\n</ul>\n</section>\n</section>\n</section>\n<section id=\"the-django-template-language\">\n<span id=\"template-language-intro\"></span><h2>The Django template language<a class=\"heading-anchor\" href=\"#the-django-template-language\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h2>\n<section id=\"syntax\">\n<h3>Syntax<a class=\"heading-anchor\" href=\"#syntax\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<aside class=\"admonition-about-this-section admonition\" role=\"note\">\n<p class=\"admonition-title\">About this section</p>\n<p>This is an overview of the Django template language's syntax. For details\nsee the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/language/\"><span class=\"doc\">language syntax reference</span></a>.</p>\n</aside>\n<p>A Django template is simply a text document or a Python string marked-up using\nthe Django template language. Some constructs are recognized and interpreted\nby the template engine. The main ones are variables and tags.</p>\n<p>A template is rendered with a context. Rendering replaces variables with their\nvalues, which are looked up in the context, and executes tags. Everything else\nis output as is.</p>\n<p>The syntax of the Django template language involves four constructs.</p>\n<section id=\"variables\">\n<h4>变量<a class=\"heading-anchor\" href=\"#variables\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>A variable outputs a value from the context, which is a dict-like object\nmapping keys to values.</p>\n<p>Variables are surrounded by <code class=\"docutils literal notranslate\">{{</code> and <code class=\"docutils literal notranslate\">}}</code> like this:</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code>My first name is <span class=\"cp\">{{</span> <span class=\"nv\">first_name</span> <span class=\"cp\">}}</span>. My last name is <span class=\"cp\">{{</span> <span class=\"nv\">last_name</span> <span class=\"cp\">}}</span>.\n</code></pre></div>\n<p>With a context of <code class=\"docutils literal notranslate\">{'first_name': 'John', 'last_name': 'Doe'}</code>, this\ntemplate renders to:</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code>My first name is John. My last name is Doe.\n</code></pre></div>\n<p>Dictionary lookup, attribute lookup and list-index lookups are implemented\nwith a dot notation:</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code><span class=\"cp\">{{</span> <span class=\"nv\">my_dict.key</span> <span class=\"cp\">}}</span>\n<span class=\"cp\">{{</span> <span class=\"nv\">my_object.attribute</span> <span class=\"cp\">}}</span>\n<span class=\"cp\">{{</span> <span class=\"nv\">my_list.0</span> <span class=\"cp\">}}</span>\n</code></pre></div>\n<p>If a variable resolves to a callable, the template system will call it with no\narguments and use its result instead of the callable.</p>\n</section>\n<section id=\"tags\">\n<h4>标签(Tags)<a class=\"heading-anchor\" href=\"#tags\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>Tags provide arbitrary logic in the rendering process.</p>\n<p>This definition is deliberately vague. For example, a tag can output content,\nserve as a control structure e.g. an &quot;if&quot; statement or a &quot;for&quot; loop, grab\ncontent from a database, or even enable access to other template tags.</p>\n<p>Tags are surrounded by <code class=\"docutils literal notranslate\">{%</code> and <code class=\"docutils literal notranslate\">%}</code> like this:</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code><span class=\"cp\">{%</span> <span class=\"k\">csrf_token</span> <span class=\"cp\">%}</span>\n</code></pre></div>\n<p>Most tags accept arguments:</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code><span class=\"cp\">{%</span> <span class=\"k\">cycle</span> <span class=\"s1\">&#39;odd&#39;</span> <span class=\"s1\">&#39;even&#39;</span> <span class=\"cp\">%}</span>\n</code></pre></div>\n<p>Some tags require beginning and ending tags:</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code><span class=\"cp\">{%</span> <span class=\"k\">if</span> <span class=\"nv\">user.is_authenticated</span> <span class=\"cp\">%}</span>Hello, <span class=\"cp\">{{</span> <span class=\"nv\">user.username</span> <span class=\"cp\">}}</span>.<span class=\"cp\">{%</span> <span class=\"k\">endif</span> <span class=\"cp\">%}</span>\n</code></pre></div>\n<p>A <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/builtins/#ref-templates-builtins-tags\"><span class=\"std std-ref\">reference of built-in tags</span></a> is\navailable as well as <a class=\"reference internal\" href=\"/zh-hans/2.0/howto/custom-template-tags/#howto-writing-custom-template-tags\"><span class=\"std std-ref\">instructions for writing custom tags</span></a>.</p>\n</section>\n<section id=\"filters\">\n<h4>过滤器<a class=\"heading-anchor\" href=\"#filters\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>Filters transform the values of variables and tag arguments.</p>\n<p>They look like this:</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code><span class=\"cp\">{{</span> <span class=\"nv\">django</span><span class=\"o\">|</span><span class=\"nf\">title</span> <span class=\"cp\">}}</span>\n</code></pre></div>\n<p>With a context of <code class=\"docutils literal notranslate\">{'django': 'the web framework for perfectionists with\ndeadlines'}</code>, this template renders to:</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code>The Web Framework For Perfectionists With Deadlines\n</code></pre></div>\n<p>Some filters take an argument:</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code><span class=\"cp\">{{</span> <span class=\"nv\">my_date</span><span class=\"o\">|</span><span class=\"nf\">date</span><span class=\"s2\">:&quot;Y-m-d&quot;</span> <span class=\"cp\">}}</span>\n</code></pre></div>\n<p>A <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/builtins/#ref-templates-builtins-filters\"><span class=\"std std-ref\">reference of built-in filters</span></a> is\navailable as well as <a class=\"reference internal\" href=\"/zh-hans/2.0/howto/custom-template-tags/#howto-writing-custom-template-filters\"><span class=\"std std-ref\">instructions for writing custom filters</span></a>.</p>\n</section>\n<section id=\"comments\">\n<h4>注释(Comments)<a class=\"heading-anchor\" href=\"#comments\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>Comments look like this:</p>\n<div class=\"code-block\" data-language=\"html+django\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Django template</span><button type=\"button\" class=\"copy-button\" data-copy hidden><span class=\"copy-button-label\">Copy</span></button></div><pre role=\"group\" tabindex=\"0\" aria-label=\"Django template code\"><code><span class=\"c\">{# this won&#39;t be rendered #}</span>\n</code></pre></div>\n<p>A <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/builtins/#std-templatetag-comment\"><code class=\"xref std std-ttag docutils literal notranslate\">{% comment %}</code></a> tag provides multi-line comments.</p>\n</section>\n</section>\n<section id=\"components\">\n<h3>Components<a class=\"heading-anchor\" href=\"#components\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h3>\n<aside class=\"admonition-about-this-section admonition\" role=\"note\">\n<p class=\"admonition-title\">About this section</p>\n<p>This is an overview of the Django template language's APIs. For details\nsee the <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/\"><span class=\"doc\">API reference</span></a>.</p>\n</aside>\n<section id=\"engine\">\n<h4>Engine<a class=\"heading-anchor\" href=\"#engine\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#django.template.Engine\" title=\"django.template.Engine\"><code class=\"xref py py-class docutils literal notranslate\">django.template.Engine</code></a> encapsulates an instance of the Django\ntemplate system. The main reason for instantiating an\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#django.template.Engine\" title=\"django.template.Engine\"><code class=\"xref py py-class docutils literal notranslate\">Engine</code></a> directly is to use the Django template\nlanguage outside of a Django project.</p>\n<p><a class=\"reference internal\" href=\"#django.template.backends.django.DjangoTemplates\" title=\"django.template.backends.django.DjangoTemplates\"><code class=\"xref py py-class docutils literal notranslate\">django.template.backends.django.DjangoTemplates</code></a> is a thin wrapper\nadapting <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#django.template.Engine\" title=\"django.template.Engine\"><code class=\"xref py py-class docutils literal notranslate\">django.template.Engine</code></a> to Django's template backend API.</p>\n</section>\n<section id=\"template\">\n<h4>Template<a class=\"heading-anchor\" href=\"#template\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#django.template.Template\" title=\"django.template.Template\"><code class=\"xref py py-class docutils literal notranslate\">django.template.Template</code></a> represents a compiled template.\nTemplates are obtained with <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#django.template.Engine.get_template\" title=\"django.template.Engine.get_template\"><code class=\"xref py py-meth docutils literal notranslate\">Engine.get_template()</code></a> or <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#django.template.Engine.from_string\" title=\"django.template.Engine.from_string\"><code class=\"xref py py-meth docutils literal notranslate\">Engine.from_string()</code></a></p>\n<p>Likewise <code class=\"docutils literal notranslate\">django.template.backends.django.Template</code> is a thin wrapper\nadapting <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#django.template.Template\" title=\"django.template.Template\"><code class=\"xref py py-class docutils literal notranslate\">django.template.Template</code></a> to the common template API.</p>\n</section>\n<section id=\"context\">\n<h4>Context<a class=\"heading-anchor\" href=\"#context\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#django.template.Context\" title=\"django.template.Context\"><code class=\"xref py py-class docutils literal notranslate\">django.template.Context</code></a> holds some metadata in addition to the\ncontext data. It is passed to <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#django.template.Template.render\" title=\"django.template.Template.render\"><code class=\"xref py py-meth docutils literal notranslate\">Template.render()</code></a> for rendering a template.</p>\n<p><a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#django.template.RequestContext\" title=\"django.template.RequestContext\"><code class=\"xref py py-class docutils literal notranslate\">django.template.RequestContext</code></a> is a subclass of\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#django.template.Context\" title=\"django.template.Context\"><code class=\"xref py py-class docutils literal notranslate\">Context</code></a> that stores the current\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/request-response/#django.http.HttpRequest\" title=\"django.http.HttpRequest\"><code class=\"xref py py-class docutils literal notranslate\">HttpRequest</code></a> and runs template context processors.</p>\n<p>The common API doesn't have an equivalent concept. Context data is passed in a\nplain <a class=\"reference external\" href=\"https://docs.python.org/3/library/stdtypes.html#dict\" title=\"(in Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\">dict</code></a> and the current <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/request-response/#django.http.HttpRequest\" title=\"django.http.HttpRequest\"><code class=\"xref py py-class docutils literal notranslate\">HttpRequest</code></a> is passed\nseparately if needed.</p>\n</section>\n<section id=\"loaders\">\n<h4>Loaders<a class=\"heading-anchor\" href=\"#loaders\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>Template loaders are responsible for locating templates, loading them, and\nreturning <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#django.template.Template\" title=\"django.template.Template\"><code class=\"xref py py-class docutils literal notranslate\">Template</code></a> objects.</p>\n<p>Django provides several <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#template-loaders\"><span class=\"std std-ref\">built-in template loaders</span></a>\nand supports <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#custom-template-loaders\"><span class=\"std std-ref\">custom template loaders</span></a>.</p>\n</section>\n<section id=\"context-processors\">\n<h4>Context processors<a class=\"heading-anchor\" href=\"#context-processors\"><span class=\"visually-hidden\">Link to this heading</span><span aria-hidden=\"true\">#</span></a></h4>\n<p>Context processors are functions that receive the current\n<a class=\"reference internal\" href=\"/zh-hans/2.0/ref/request-response/#django.http.HttpRequest\" title=\"django.http.HttpRequest\"><code class=\"xref py py-class docutils literal notranslate\">HttpRequest</code></a> as an argument and return a <a class=\"reference external\" href=\"https://docs.python.org/3/library/stdtypes.html#dict\" title=\"(in Python v3.14)\"><code class=\"xref py py-class docutils literal notranslate\">dict</code></a> of\ndata to be added to the rendering context.</p>\n<p>Their main use is to add common data shared by all templates to the context\nwithout repeating code in every view.</p>\n<p>Django provides many <a class=\"reference internal\" href=\"/zh-hans/2.0/ref/templates/api/#context-processors\"><span class=\"std std-ref\">built-in context processors</span></a>.\nImplementing a custom context processor is as simple as defining a function.</p>\n</section>\n</section>\n</section>","rootId":"module-django.template","toc":[{"title":"模板引擎的支持","anchor":"support-for-template-engines","children":[{"title":"配置","anchor":"configuration","children":[]},{"title":"Usage","anchor":"usage","children":[]},{"title":"内置后端","anchor":"module-django.template.backends.django","children":[]},{"title":"Custom backends","anchor":"custom-backends","children":[]},{"title":"Debug integration for custom engines","anchor":"debug-integration-for-custom-engines","children":[{"title":"Template postmortem","anchor":"template-postmortem","children":[]},{"title":"Contextual line information","anchor":"contextual-line-information","children":[]},{"title":"Origin API and 3rd-party integration","anchor":"origin-api-and-3rd-party-integration","children":[]}]}]},{"title":"The Django template language","anchor":"the-django-template-language","children":[{"title":"Syntax","anchor":"syntax","children":[{"title":"变量","anchor":"variables","children":[]},{"title":"标签(Tags)","anchor":"tags","children":[]},{"title":"过滤器","anchor":"filters","children":[]},{"title":"注释(Comments)","anchor":"comments","children":[]}]},{"title":"Components","anchor":"components","children":[{"title":"Engine","anchor":"engine","children":[]},{"title":"Template","anchor":"template","children":[]},{"title":"Context","anchor":"context","children":[]},{"title":"Loaders","anchor":"loaders","children":[]},{"title":"Context processors","anchor":"context-processors","children":[]}]}]}],"breadcrumbs":[{"docname":"topics/index","title":"Using Django","url":"/zh-hans/2.0/topics/"}],"prev":{"docname":"topics/forms/media","title":"表单资源（ Media 类）","url":"/zh-hans/2.0/topics/forms/media/"},"next":{"docname":"topics/class-based-views/index","title":"Class-based views","url":"/zh-hans/2.0/topics/class-based-views/"},"formats":{"html":"/zh-hans/2.0/topics/templates/","markdown":"/zh-hans/2.0/topics/templates.md","json":"/zh-hans/2.0/topics/templates.json"},"source":"https://github.com/django/django/blob/stable/2.0.x/docs/topics/templates.txt","official":"https://docs.djangoproject.com/zh-hans/2.0/topics/templates/","inVersions":["6.1","6.0","5.2","5.1","5.0","4.2","4.1","4.0","3.2","3.1","3.0","2.2","2.1","2.0"],"inLocales":["en","zh-hans","fr","ja","id","pt-br","ko","es","el","pl"]}