{"title":"模板","version":"3.0","locale":"zh-hans","docname":"topics/templates","url":"/zh-hans/3.0/topics/templates/","canonical":"https://djangodocs.dev/zh-hans/3.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/3.0/ref/settings/#std-setting-TEMPLATES\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">TEMPLATES</span></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\"><span class=\"pre\">settings.py</span></code> generated by the <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/django-admin/#django-admin-startproject\"><code class=\"xref std std-djadmin docutils literal notranslate\"><span class=\"pre\">startproject</span></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><span class=\"n\">TEMPLATES</span> <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/3.0/ref/settings/#std-setting-TEMPLATES-BACKEND\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">BACKEND</span></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\"><span class=\"pre\">django.template.backends.django.DjangoTemplates</span></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\"><span class=\"pre\">django.template.backends.jinja2.Jinja2</span></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/3.0/ref/settings/#std-setting-TEMPLATES-DIRS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">DIRS</span></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/3.0/ref/settings/#std-setting-TEMPLATES-APP_DIRS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">APP_DIRS</span></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/3.0/ref/settings/#std-setting-TEMPLATES-NAME\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">NAME</span></code></a> for each engine.</p>\n<p><a class=\"reference internal\" href=\"/zh-hans/3.0/ref/settings/#std-setting-TEMPLATES-OPTIONS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">OPTIONS</span></code></a> contains backend-specific settings.</p>\n</section>\n<section id=\"usage\">\n<h3>用法<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\"><span class=\"pre\">django.template.loader</span></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\"><span class=\"pre\">get_template</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">template_name</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">using</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></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\"><span class=\"pre\">Template</span></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\"><span class=\"pre\">Template</span></code> class.</p>\n<p><code class=\"docutils literal notranslate\"><span class=\"pre\">get_template()</span></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\"><span class=\"pre\">TemplateDoesNotExist</span></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\"><span class=\"pre\">TemplateSyntaxError</span></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/3.0/ref/settings/#std-setting-TEMPLATES-NAME\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">NAME</span></code></a> in the <code class=\"docutils literal notranslate\"><span class=\"pre\">using</span></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\"><span class=\"pre\">select_template</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">template_name_list</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">using</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></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\"><span class=\"pre\">select_template()</span></code> is just like <code class=\"docutils literal notranslate\"><span class=\"pre\">get_template()</span></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\"><span class=\"pre\">django.template</span></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\"><span class=\"pre\">exception</span></span><span class=\"w\"> </span></em><span class=\"sig-name descname\"><span class=\"pre\">TemplateDoesNotExist</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">msg</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">tried</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">backend</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">chain</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></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\"><span class=\"pre\">backend</span></code></dt><dd><p>The template backend instance from which the exception originated.</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\"><span class=\"pre\">tried</span></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\"><span class=\"pre\">(origin,</span> <span class=\"pre\">status)</span></code>, where\n<code class=\"docutils literal notranslate\"><span class=\"pre\">origin</span></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\"><span class=\"pre\">status</span></code> is a string with the reason the template wasn't found.</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\"><span class=\"pre\">chain</span></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\"><span class=\"pre\">TemplateDoesNotExist</span></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\"><span class=\"pre\">get_template()</span></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\"><span class=\"pre\">exception</span></span><span class=\"w\"> </span></em><span class=\"sig-name descname\"><span class=\"pre\">TemplateSyntaxError</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">msg</span></span></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\"><span class=\"pre\">Template</span></code> objects returned by <code class=\"docutils literal notranslate\"><span class=\"pre\">get_template()</span></code> and <code class=\"docutils literal notranslate\"><span class=\"pre\">select_template()</span></code>\nmust provide a <code class=\"docutils literal notranslate\"><span class=\"pre\">render()</span></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\"><span class=\"pre\">Template.</span></span><span class=\"sig-name descname\"><span class=\"pre\">render</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">context</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">request</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></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\"><span class=\"pre\">context</span></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\"><span class=\"pre\">dict</span></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\"><span class=\"pre\">request</span></code> is provided, it must be an <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/request-response/#django.http.HttpRequest\" title=\"django.http.HttpRequest\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">HttpRequest</span></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/3.0/ref/settings/#std-setting-TEMPLATES\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">TEMPLATES</span></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><span class=\"n\">TEMPLATES</span> <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\"><span class=\"pre\">get_template('story_detail.html')</span></code>, here are the files Django\nwill look for, in order:</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">/home/html/example.com/story_detail.html</span></code> (<code class=\"docutils literal notranslate\"><span class=\"pre\">'django'</span></code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">/home/html/default/story_detail.html</span></code> (<code class=\"docutils literal notranslate\"><span class=\"pre\">'django'</span></code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">/home/html/jinja2/story_detail.html</span></code> (<code class=\"docutils literal notranslate\"><span class=\"pre\">'jinja2'</span></code> engine)</p></li>\n</ul>\n<p>If you call <code class=\"docutils literal notranslate\"><span class=\"pre\">select_template(['story_253_detail.html',</span> <span class=\"pre\">'story_detail.html'])</span></code>,\nhere's what Django will look for:</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">/home/html/example.com/story_253_detail.html</span></code> (<code class=\"docutils literal notranslate\"><span class=\"pre\">'django'</span></code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">/home/html/default/story_253_detail.html</span></code> (<code class=\"docutils literal notranslate\"><span class=\"pre\">'django'</span></code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">/home/html/jinja2/story_253_detail.html</span></code> (<code class=\"docutils literal notranslate\"><span class=\"pre\">'jinja2'</span></code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">/home/html/example.com/story_detail.html</span></code> (<code class=\"docutils literal notranslate\"><span class=\"pre\">'django'</span></code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">/home/html/default/story_detail.html</span></code> (<code class=\"docutils literal notranslate\"><span class=\"pre\">'django'</span></code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">/home/html/jinja2/story_detail.html</span></code> (<code class=\"docutils literal notranslate\"><span class=\"pre\">'jinja2'</span></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\">\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\"><span class=\"pre\">select_template()</span></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\"><span class=\"pre\">select_template(['story_%s_detail.html'</span> <span class=\"pre\">%</span> <span class=\"pre\">story.id,</span>\n<span class=\"pre\">'story_detail.html'])</span></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, 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><span class=\"n\">get_template</span><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/3.0/ref/settings/#std-setting-TEMPLATES\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">TEMPLATES</span></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\"><span class=\"pre\">/home/html/example.com/news/story_detail.html</span></code> (<code class=\"docutils literal notranslate\"><span class=\"pre\">'django'</span></code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">/home/html/default/news/story_detail.html</span></code> (<code class=\"docutils literal notranslate\"><span class=\"pre\">'django'</span></code> engine)</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">/home/html/jinja2/news/story_detail.html</span></code> (<code class=\"docutils literal notranslate\"><span class=\"pre\">'jinja2'</span></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\"><span class=\"pre\">render_to_string</span></span><span class=\"sig-paren\">(</span><em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">template_name</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">context</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">request</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></span></em>, <em class=\"sig-param\"><span class=\"n\"><span class=\"pre\">using</span></span><span class=\"o\"><span class=\"pre\">=</span></span><span class=\"default_value\"><span class=\"pre\">None</span></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\"><span class=\"pre\">render_to_string()</span></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\"><span class=\"pre\">get_template()</span></code></a> ，并立即调用它的 <code class=\"docutils literal notranslate\"><span class=\"pre\">render()</span></code> 方法。它需要下面的参数。</p>\n<dl class=\"simple\">\n<dt><code class=\"docutils literal notranslate\"><span class=\"pre\">template_name</span></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\"><span class=\"pre\">select_template()</span></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\"><span class=\"pre\">get_template()</span></code></a> 找到模板。</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\"><span class=\"pre\">context</span></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\"><span class=\"pre\">dict</span></code></a> 用作模板的渲染上下文。</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\"><span class=\"pre\">request</span></code></dt><dd><p> 可选项 <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/request-response/#django.http.HttpRequest\" title=\"django.http.HttpRequest\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">HttpRequest</span></code></a> 在模板的渲染过程中可用。</p>\n</dd>\n<dt><code class=\"docutils literal notranslate\"><span class=\"pre\">using</span></code></dt><dd><p>可选的模板引擎 <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/settings/#std-setting-TEMPLATES-NAME\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">NAME</span></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=\"w\"> </span><span class=\"nn\">django.template.loader</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">render_to_string</span>\n<span class=\"n\">rendered</span> <span class=\"o\">=</span> <span class=\"n\">render_to_string</span><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/3.0/topics/http/shortcuts/#django.shortcuts.render\" title=\"django.shortcuts.render\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">render()</span></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\"><span class=\"pre\">render_to_string()</span></code></a> ，并将结果提供给 <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/request-response/#django.http.HttpResponse\" title=\"django.http.HttpResponse\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">HttpResponse</span></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\"><span class=\"pre\">engines</span></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\"><span class=\"pre\">django.template.engines</span></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=\"w\"> </span><span class=\"nn\">django.template</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">engines</span>\n\n<span class=\"n\">django_engine</span> <span class=\"o\">=</span> <span class=\"n\">engines</span><span class=\"p\">[</span><span class=\"s1\">&#39;django&#39;</span><span class=\"p\">]</span>\n<span class=\"n\">template</span> <span class=\"o\">=</span> <span class=\"n\">django_engine</span><span class=\"o\">.</span><span class=\"n\">from_string</span><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/3.0/ref/settings/#std-setting-TEMPLATES-NAME\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">NAME</span></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\"><span class=\"pre\">class</span></span><span class=\"w\"> </span></em><span class=\"sig-name descname\"><span class=\"pre\">DjangoTemplates</span></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/3.0/ref/settings/#std-setting-TEMPLATES-BACKEND\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">BACKEND</span></code></a> 为 <code class=\"docutils literal notranslate\"><span class=\"pre\">'django.template.backends.django.DjangoTemplates'</span></code>，以配置 Django 模板引擎。</p>\n<p>When <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/settings/#std-setting-TEMPLATES-APP_DIRS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">APP_DIRS</span></code></a> is <code class=\"docutils literal notranslate\"><span class=\"pre\">True</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">DjangoTemplates</span></code>\nengines look for templates in the <code class=\"docutils literal notranslate\"><span class=\"pre\">templates</span></code> subdirectory of installed\napplications. This generic name was kept for backwards-compatibility.</p>\n<p><code class=\"docutils literal notranslate\"><span class=\"pre\">DjangoTemplates</span></code> engines accept the following <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/settings/#std-setting-TEMPLATES-OPTIONS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">OPTIONS</span></code></a>:</p>\n<ul>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'autoescape'</span></code>: a boolean that controls whether HTML autoescaping is\nenabled.</p>\n<p>It defaults to <code class=\"docutils literal notranslate\"><span class=\"pre\">True</span></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\"><span class=\"pre\">False</span></code> if you're rendering non-HTML templates!</p>\n</aside>\n</li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'context_processors'</span></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\"><span class=\"pre\">dict</span></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/3.0/ref/templates/api/#django.template.RequestContext\" title=\"django.template.RequestContext\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">RequestContext</span></code></a> for more information.</p>\n</li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'debug'</span></code>: a boolean that turns on/off template debug mode. If it is\n<code class=\"docutils literal notranslate\"><span class=\"pre\">True</span></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/3.0/ref/settings/#std-setting-DEBUG\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">DEBUG</span></code></a> setting.</p>\n</li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'loaders'</span></code>: a list of dotted Python paths to template loader classes.\nEach <code class=\"docutils literal notranslate\"><span class=\"pre\">Loader</span></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\"><span class=\"pre\">Loader</span></code> class name, and subsequent items are\npassed to the <code class=\"docutils literal notranslate\"><span class=\"pre\">Loader</span></code> during initialization.</p>\n<p>The default depends on the values of <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/settings/#std-setting-TEMPLATES-DIRS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">DIRS</span></code></a> and\n<a class=\"reference internal\" href=\"/zh-hans/3.0/ref/settings/#std-setting-TEMPLATES-APP_DIRS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">APP_DIRS</span></code></a>.</p>\n<p>See <a class=\"reference internal\" href=\"/zh-hans/3.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\"><span class=\"pre\">'string_if_invalid'</span></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/3.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\"><span class=\"pre\">'file_charset'</span></code>: the charset used to read template files on disk.</p>\n<p>It defaults to <code class=\"docutils literal notranslate\"><span class=\"pre\">'utf-8'</span></code>.</p>\n</li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'libraries'</span></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><span class=\"n\">OPTIONS</span><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/3.0/ref/templates/builtins/#std-templatetag-load\"><code class=\"xref std std-ttag docutils literal notranslate\"><span class=\"pre\">{%</span> <span class=\"pre\">load</span> <span class=\"pre\">%}</span></code></a> tag.</p>\n</li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'builtins'</span></code>: A list of dotted Python paths of template tag modules to\nadd to <a class=\"reference internal\" href=\"/zh-hans/3.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><span class=\"n\">OPTIONS</span><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/3.0/ref/templates/builtins/#std-templatetag-load\"><code class=\"xref std std-ttag docutils literal notranslate\"><span class=\"pre\">{%</span> <span class=\"pre\">load</span> <span class=\"pre\">%}</span></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\"><span class=\"pre\">class</span></span><span class=\"w\"> </span></em><span class=\"sig-name descname\"><span class=\"pre\">Jinja2</span></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=\"console\" data-console><div class=\"console-panel\" data-platform=\"unix\"><p class=\"console-label\" id=\"console-0-unix-label\">Linux / macOS</p><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>python<span class=\"w\"> </span>-m<span class=\"w\"> </span>pip<span class=\"w\"> </span>install<span class=\"w\"> </span>Jinja2\n</code></pre></div>\n</div><div class=\"console-panel\" data-platform=\"windows\"><p class=\"console-label\" id=\"console-0-windows-label\">Windows</p><div class=\"code-block\" data-language=\"doscon\"><div class=\"code-block-toolbar\"><span class=\"code-block-language\">Windows</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=\"Windows shell\"><code><span class=\"gp\">...\\&gt;</span> py -m pip install Jinja2\n</code></pre></div></div></div>\n<p>Set <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/settings/#std-setting-TEMPLATES-BACKEND\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">BACKEND</span></code></a> to\n<code class=\"docutils literal notranslate\"><span class=\"pre\">'django.template.backends.jinja2.Jinja2'</span></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/3.0/ref/settings/#std-setting-TEMPLATES-APP_DIRS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">APP_DIRS</span></code></a> is <code class=\"docutils literal notranslate\"><span class=\"pre\">True</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">Jinja2</span></code> engines\nlook for templates in the <code class=\"docutils literal notranslate\"><span class=\"pre\">jinja2</span></code> subdirectory of installed applications.</p>\n<p>The most important entry in <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/settings/#std-setting-TEMPLATES-OPTIONS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">OPTIONS</span></code></a> is\n<code class=\"docutils literal notranslate\"><span class=\"pre\">'environment'</span></code>. It's a dotted Python path to a callable returning a Jinja2\nenvironment. It defaults to <code class=\"docutils literal notranslate\"><span class=\"pre\">'jinja2.Environment'</span></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\"><span class=\"pre\">'autoescape'</span></code>: <code class=\"docutils literal notranslate\"><span class=\"pre\">True</span></code></p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'loader'</span></code>: a loader configured for <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/settings/#std-setting-TEMPLATES-DIRS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">DIRS</span></code></a> and\n<a class=\"reference internal\" href=\"/zh-hans/3.0/ref/settings/#std-setting-TEMPLATES-APP_DIRS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">APP_DIRS</span></code></a></p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'auto_reload'</span></code>: <code class=\"docutils literal notranslate\"><span class=\"pre\">settings.DEBUG</span></code></p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'undefined'</span></code>: <code class=\"docutils literal notranslate\"><span class=\"pre\">DebugUndefined</span> <span class=\"pre\">if</span> <span class=\"pre\">settings.DEBUG</span> <span class=\"pre\">else</span> <span class=\"pre\">Undefined</span></code></p></li>\n</ul>\n<p><code class=\"docutils literal notranslate\"><span class=\"pre\">Jinja2</span></code> engines also accept the following <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/settings/#std-setting-TEMPLATES-OPTIONS\"><code class=\"xref std std-setting docutils literal notranslate\"><span class=\"pre\">OPTIONS</span></code></a>:</p>\n<ul>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'context_processors'</span></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\"><span class=\"pre\">dict</span></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\">\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\"><span class=\"pre\">jinja2.Environment</span></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\"><span class=\"pre\">jinja2.Environment</span></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\nmore in line with the design of Jinja2.</p>\n</aside>\n</li>\n</ul>\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/3.0/topics/http/shortcuts/#django.shortcuts.render\" title=\"django.shortcuts.render\"><code class=\"xref py py-func docutils literal notranslate\"><span class=\"pre\">render()</span></code></a>),\nthe <code class=\"docutils literal notranslate\"><span class=\"pre\">Jinja2</span></code> backend adds the globals <code class=\"docutils literal notranslate\"><span class=\"pre\">request</span></code>, <code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_input</span></code>, and\n<code class=\"docutils literal notranslate\"><span class=\"pre\">csrf_token</span></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\"><span class=\"pre\">myproject/jinja2.py</span></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=\"w\"> </span><span class=\"nn\">django.templatetags.static</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">static</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.urls</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">reverse</span>\n\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">jinja2</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">Environment</span>\n\n\n<span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">environment</span><span class=\"p\">(</span><span class=\"o\">**</span><span class=\"n\">options</span><span class=\"p\">):</span>\n    <span class=\"n\">env</span> <span class=\"o\">=</span> <span class=\"n\">Environment</span><span class=\"p\">(</span><span class=\"o\">**</span><span class=\"n\">options</span><span class=\"p\">)</span>\n    <span class=\"n\">env</span><span class=\"o\">.</span><span class=\"n\">globals</span><span class=\"o\">.</span><span class=\"n\">update</span><span class=\"p\">({</span>\n        <span class=\"s1\">&#39;static&#39;</span><span class=\"p\">:</span> <span class=\"n\">static</span><span class=\"p\">,</span>\n        <span class=\"s1\">&#39;url&#39;</span><span class=\"p\">:</span> <span class=\"n\">reverse</span><span class=\"p\">,</span>\n    <span class=\"p\">})</span>\n    <span class=\"k\">return</span> <span class=\"n\">env</span>\n</code></pre></div>\n<p>and set the <code class=\"docutils literal notranslate\"><span class=\"pre\">'environment'</span></code> option to <code class=\"docutils literal notranslate\"><span class=\"pre\">'myproject.jinja2.environment'</span></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 by calling a function in Jinja2\ntemplates, as shown in the example above. Jinja2's global namespace removes the\nneed for template context processors. The Django template language doesn't have\nan 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\"><span class=\"pre\">django.template.backends.base.BaseEngine</span></code>. It must implement\n<code class=\"docutils literal notranslate\"><span class=\"pre\">get_template()</span></code> and optionally <code class=\"docutils literal notranslate\"><span class=\"pre\">from_string()</span></code>. Here's an example for a\nfictional <code class=\"docutils literal notranslate\"><span class=\"pre\">foobar</span></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=\"w\"> </span><span class=\"nn\">django.template</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">TemplateDoesNotExist</span><span class=\"p\">,</span> <span class=\"n\">TemplateSyntaxError</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.template.backends.base</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">BaseEngine</span>\n<span class=\"kn\">from</span><span class=\"w\"> </span><span class=\"nn\">django.template.backends.utils</span><span class=\"w\"> </span><span class=\"kn\">import</span> <span class=\"n\">csrf_input_lazy</span><span class=\"p\">,</span> <span class=\"n\">csrf_token_lazy</span>\n\n<span class=\"kn\">import</span><span class=\"w\"> </span><span class=\"nn\">foobar</span>\n\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">FooBar</span><span class=\"p\">(</span><span class=\"n\">BaseEngine</span><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    <span class=\"n\">app_dirname</span> <span class=\"o\">=</span> <span class=\"s1\">&#39;foobar&#39;</span>\n\n    <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"fm\">__init__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">params</span><span class=\"p\">):</span>\n        <span class=\"n\">params</span> <span class=\"o\">=</span> <span class=\"n\">params</span><span class=\"o\">.</span><span class=\"n\">copy</span><span class=\"p\">()</span>\n        <span class=\"n\">options</span> <span class=\"o\">=</span> <span class=\"n\">params</span><span class=\"o\">.</span><span class=\"n\">pop</span><span class=\"p\">(</span><span class=\"s1\">&#39;OPTIONS&#39;</span><span class=\"p\">)</span><span class=\"o\">.</span><span class=\"n\">copy</span><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><span class=\"n\">params</span><span class=\"p\">)</span>\n\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">engine</span> <span class=\"o\">=</span> <span class=\"n\">foobar</span><span class=\"o\">.</span><span class=\"n\">Engine</span><span class=\"p\">(</span><span class=\"o\">**</span><span class=\"n\">options</span><span class=\"p\">)</span>\n\n    <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">from_string</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">template_code</span><span class=\"p\">):</span>\n        <span class=\"k\">try</span><span class=\"p\">:</span>\n            <span class=\"k\">return</span> <span class=\"n\">Template</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">engine</span><span class=\"o\">.</span><span class=\"n\">from_string</span><span class=\"p\">(</span><span class=\"n\">template_code</span><span class=\"p\">))</span>\n        <span class=\"k\">except</span> <span class=\"n\">foobar</span><span class=\"o\">.</span><span class=\"n\">TemplateCompilationFailed</span> <span class=\"k\">as</span> <span class=\"n\">exc</span><span class=\"p\">:</span>\n            <span class=\"k\">raise</span> <span class=\"n\">TemplateSyntaxError</span><span class=\"p\">(</span><span class=\"n\">exc</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">)</span>\n\n    <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">get_template</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">template_name</span><span class=\"p\">):</span>\n        <span class=\"k\">try</span><span class=\"p\">:</span>\n            <span class=\"k\">return</span> <span class=\"n\">Template</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">engine</span><span class=\"o\">.</span><span class=\"n\">get_template</span><span class=\"p\">(</span><span class=\"n\">template_name</span><span class=\"p\">))</span>\n        <span class=\"k\">except</span> <span class=\"n\">foobar</span><span class=\"o\">.</span><span class=\"n\">TemplateNotFound</span> <span class=\"k\">as</span> <span class=\"n\">exc</span><span class=\"p\">:</span>\n            <span class=\"k\">raise</span> <span class=\"n\">TemplateDoesNotExist</span><span class=\"p\">(</span><span class=\"n\">exc</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">,</span> <span class=\"n\">backend</span><span class=\"o\">=</span><span class=\"bp\">self</span><span class=\"p\">)</span>\n        <span class=\"k\">except</span> <span class=\"n\">foobar</span><span class=\"o\">.</span><span class=\"n\">TemplateCompilationFailed</span> <span class=\"k\">as</span> <span class=\"n\">exc</span><span class=\"p\">:</span>\n            <span class=\"k\">raise</span> <span class=\"n\">TemplateSyntaxError</span><span class=\"p\">(</span><span class=\"n\">exc</span><span class=\"o\">.</span><span class=\"n\">args</span><span class=\"p\">)</span>\n\n\n<span class=\"k\">class</span><span class=\"w\"> </span><span class=\"nc\">Template</span><span class=\"p\">:</span>\n\n    <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"fm\">__init__</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">template</span><span class=\"p\">):</span>\n        <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">template</span> <span class=\"o\">=</span> <span class=\"n\">template</span>\n\n    <span class=\"k\">def</span><span class=\"w\"> </span><span class=\"nf\">render</span><span class=\"p\">(</span><span class=\"bp\">self</span><span class=\"p\">,</span> <span class=\"n\">context</span><span class=\"o\">=</span><span class=\"kc\">None</span><span class=\"p\">,</span> <span class=\"n\">request</span><span class=\"o\">=</span><span class=\"kc\">None</span><span class=\"p\">):</span>\n        <span class=\"k\">if</span> <span class=\"n\">context</span> <span class=\"ow\">is</span> <span class=\"kc\">None</span><span class=\"p\">:</span>\n            <span class=\"n\">context</span> <span class=\"o\">=</span> <span class=\"p\">{}</span>\n        <span class=\"k\">if</span> <span class=\"n\">request</span> <span class=\"ow\">is</span> <span class=\"ow\">not</span> <span class=\"kc\">None</span><span class=\"p\">:</span>\n            <span class=\"n\">context</span><span class=\"p\">[</span><span class=\"s1\">&#39;request&#39;</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"n\">request</span>\n            <span class=\"n\">context</span><span class=\"p\">[</span><span class=\"s1\">&#39;csrf_input&#39;</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"n\">csrf_input_lazy</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">)</span>\n            <span class=\"n\">context</span><span class=\"p\">[</span><span class=\"s1\">&#39;csrf_token&#39;</span><span class=\"p\">]</span> <span class=\"o\">=</span> <span class=\"n\">csrf_token_lazy</span><span class=\"p\">(</span><span class=\"n\">request</span><span class=\"p\">)</span>\n        <span class=\"k\">return</span> <span class=\"bp\">self</span><span class=\"o\">.</span><span class=\"n\">template</span><span class=\"o\">.</span><span class=\"n\">render</span><span class=\"p\">(</span><span class=\"n\">context</span><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\"><span class=\"pre\">TemplateDoesNotExist</span></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/3.0/_images/postmortem.png\" src=\"/zh-hans/3.0/_images/postmortem.png\" />\n<p>Custom engines can populate the postmortem by passing the <code class=\"docutils literal notranslate\"><span class=\"pre\">backend</span></code> and\n<code class=\"docutils literal notranslate\"><span class=\"pre\">tried</span></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\"><span class=\"pre\">TemplateDoesNotExist</span></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/3.0/_images/template-lines.png\" src=\"/zh-hans/3.0/_images/template-lines.png\" />\n<p>Custom engines can populate this information by setting a <code class=\"docutils literal notranslate\"><span class=\"pre\">template_debug</span></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\"><span class=\"pre\">dict</span></code></a> with the following values:</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'name'</span></code>: The name of the template in which the exception occurred.</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'message'</span></code>: The exception message.</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'source_lines'</span></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\"><span class=\"pre\">'line'</span></code>: The line number on which the exception occurred.</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'before'</span></code>: The content on the error line before the token that raised the\nerror.</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'during'</span></code>: The token that raised the error.</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'after'</span></code>: The content on the error line after the token that raised the\nerror.</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'total'</span></code>: The number of lines in <code class=\"docutils literal notranslate\"><span class=\"pre\">source_lines</span></code>.</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'top'</span></code>: The line number where <code class=\"docutils literal notranslate\"><span class=\"pre\">source_lines</span></code> starts.</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'bottom'</span></code>: The line number where <code class=\"docutils literal notranslate\"><span class=\"pre\">source_lines</span></code> ends.</p></li>\n</ul>\n<p>Given the above template error, <code class=\"docutils literal notranslate\"><span class=\"pre\">template_debug</span></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/3.0/ref/templates/api/#django.template.base.Origin\" title=\"django.template.base.Origin\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">Origin</span></code></a> object available\nthrough the <code class=\"docutils literal notranslate\"><span class=\"pre\">template.origin</span></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\"><span class=\"pre\">template.origin</span></code> information by\ncreating an object that specifies the following attributes:</p>\n<ul class=\"simple\">\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'name'</span></code>: The full path to the template.</p></li>\n<li><p><code class=\"docutils literal notranslate\"><span class=\"pre\">'template_name'</span></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\"><span class=\"pre\">'loader_name'</span></code>: An optional string identifying the function or class used\nto load the template, e.g. <code class=\"docutils literal notranslate\"><span class=\"pre\">django.template.loaders.filesystem.Loader</span></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\">\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/3.0/ref/templates/language/\"><span class=\"doc\">language syntax reference</span></a>.</p>\n</aside>\n<p>A Django template is a text document or a Python string marked-up using the\nDjango template language. Some constructs are recognized and interpreted by the\ntemplate 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\"><span class=\"pre\">{{</span></code> and <code class=\"docutils literal notranslate\"><span class=\"pre\">}}</span></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\"><span class=\"pre\">{'first_name':</span> <span class=\"pre\">'John',</span> <span class=\"pre\">'last_name':</span> <span class=\"pre\">'Doe'}</span></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\"><span class=\"pre\">{%</span></code> and <code class=\"docutils literal notranslate\"><span class=\"pre\">%}</span></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/3.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/3.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\"><span class=\"pre\">{'django':</span> <span class=\"pre\">'the</span> <span class=\"pre\">web</span> <span class=\"pre\">framework</span> <span class=\"pre\">for</span> <span class=\"pre\">perfectionists</span> <span class=\"pre\">with</span>\n<span class=\"pre\">deadlines'}</span></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/3.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/3.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/3.0/ref/templates/builtins/#std-templatetag-comment\"><code class=\"xref std std-ttag docutils literal notranslate\"><span class=\"pre\">{%</span> <span class=\"pre\">comment</span> <span class=\"pre\">%}</span></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\">\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/3.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/3.0/ref/templates/api/#django.template.Engine\" title=\"django.template.Engine\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">django.template.Engine</span></code></a> encapsulates an instance of the Django\ntemplate system. The main reason for instantiating an\n<a class=\"reference internal\" href=\"/zh-hans/3.0/ref/templates/api/#django.template.Engine\" title=\"django.template.Engine\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">Engine</span></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\"><span class=\"pre\">django.template.backends.django.DjangoTemplates</span></code></a> is a thin wrapper\nadapting <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/templates/api/#django.template.Engine\" title=\"django.template.Engine\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">django.template.Engine</span></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/3.0/ref/templates/api/#django.template.Template\" title=\"django.template.Template\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">django.template.Template</span></code></a> represents a compiled template.\nTemplates are obtained with <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/templates/api/#django.template.Engine.get_template\" title=\"django.template.Engine.get_template\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">Engine.get_template()</span></code></a> or <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/templates/api/#django.template.Engine.from_string\" title=\"django.template.Engine.from_string\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">Engine.from_string()</span></code></a></p>\n<p>Likewise <code class=\"docutils literal notranslate\"><span class=\"pre\">django.template.backends.django.Template</span></code> is a thin wrapper\nadapting <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/templates/api/#django.template.Template\" title=\"django.template.Template\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">django.template.Template</span></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/3.0/ref/templates/api/#django.template.Context\" title=\"django.template.Context\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">django.template.Context</span></code></a> holds some metadata in addition to the\ncontext data. It is passed to <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/templates/api/#django.template.Template.render\" title=\"django.template.Template.render\"><code class=\"xref py py-meth docutils literal notranslate\"><span class=\"pre\">Template.render()</span></code></a> for rendering a template.</p>\n<p><a class=\"reference internal\" href=\"/zh-hans/3.0/ref/templates/api/#django.template.RequestContext\" title=\"django.template.RequestContext\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">django.template.RequestContext</span></code></a> is a subclass of\n<a class=\"reference internal\" href=\"/zh-hans/3.0/ref/templates/api/#django.template.Context\" title=\"django.template.Context\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">Context</span></code></a> that stores the current\n<a class=\"reference internal\" href=\"/zh-hans/3.0/ref/request-response/#django.http.HttpRequest\" title=\"django.http.HttpRequest\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">HttpRequest</span></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\"><span class=\"pre\">dict</span></code></a> and the current <a class=\"reference internal\" href=\"/zh-hans/3.0/ref/request-response/#django.http.HttpRequest\" title=\"django.http.HttpRequest\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">HttpRequest</span></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/3.0/ref/templates/api/#django.template.Template\" title=\"django.template.Template\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">Template</span></code></a> objects.</p>\n<p>Django provides several <a class=\"reference internal\" href=\"/zh-hans/3.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/3.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/3.0/ref/request-response/#django.http.HttpRequest\" title=\"django.http.HttpRequest\"><code class=\"xref py py-class docutils literal notranslate\"><span class=\"pre\">HttpRequest</span></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\"><span class=\"pre\">dict</span></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/3.0/ref/templates/api/#context-processors\"><span class=\"std std-ref\">built-in context processors</span></a>,\nand you can implement your own additional context processors, too.</p>\n</section>\n</section>\n</section>","rootId":"module-django.template","toc":[{"title":"模板引擎的支持","anchor":"support-for-template-engines","children":[{"title":"配置","anchor":"configuration","children":[]},{"title":"用法","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":"使用 Django","url":"/zh-hans/3.0/topics/"}],"prev":{"docname":"topics/forms/media","title":"表单资源（ Media 类）","url":"/zh-hans/3.0/topics/forms/media/"},"next":{"docname":"topics/class-based-views/index","title":"基于类的视图","url":"/zh-hans/3.0/topics/class-based-views/"},"formats":{"html":"/zh-hans/3.0/topics/templates/","markdown":"/zh-hans/3.0/topics/templates.md","json":"/zh-hans/3.0/topics/templates.json"},"source":"https://github.com/django/django/blob/stable/3.0.x/docs/topics/templates.txt","official":"https://docs.djangoproject.com/zh-hans/3.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"]}