<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang=""> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Templates — Django 1.8.19 documentation</title> <link rel="stylesheet" href="../_static/default.css" type="text/css" /> <link rel="stylesheet" href="../_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: '../', VERSION: '1.8.19', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="../_static/jquery.js"></script> <script type="text/javascript" src="../_static/underscore.js"></script> <script type="text/javascript" src="../_static/doctools.js"></script> <link rel="index" title="Index" href="../genindex.html" /> <link rel="search" title="Search" href="../search.html" /> <link rel="top" title="Django 1.8.19 documentation" href="../contents.html" /> <link rel="up" title="Using Django" href="index.html" /> <link rel="next" title="Class-based views" href="class-based-views/index.html" /> <link rel="prev" title="Form Assets (the Media class)" href="forms/media.html" /> <script type="text/javascript" src="../templatebuiltins.js"></script> <script type="text/javascript"> (function($) { if (!django_template_builtins) { // templatebuiltins.js missing, do nothing. return; } $(document).ready(function() { // Hyperlink Django template tags and filters var base = "../ref/templates/builtins.html"; if (base == "#") { // Special case for builtins.html itself base = ""; } // Tags are keywords, class '.k' $("div.highlight\\-html\\+django span.k").each(function(i, elem) { var tagname = $(elem).text(); if ($.inArray(tagname, django_template_builtins.ttags) != -1) { var fragment = tagname.replace(/_/, '-'); $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>"); } }); // Filters are functions, class '.nf' $("div.highlight\\-html\\+django span.nf").each(function(i, elem) { var filtername = $(elem).text(); if ($.inArray(filtername, django_template_builtins.tfilters) != -1) { var fragment = filtername.replace(/_/, '-'); $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>"); } }); }); })(jQuery); </script> </head> <body role="document"> <div class="document"> <div id="custom-doc" class="yui-t6"> <div id="hd"> <h1><a href="../index.html">Django 1.8.19 documentation</a></h1> <div id="global-nav"> <a title="Home page" href="../index.html">Home</a> | <a title="Table of contents" href="../contents.html">Table of contents</a> | <a title="Global index" href="../genindex.html">Index</a> | <a title="Module index" href="../py-modindex.html">Modules</a> </div> <div class="nav"> « <a href="forms/media.html" title="Form Assets (the <code class="docutils literal"><span class="pre">Media</span></code> class)">previous</a> | <a href="index.html" title="Using Django" accesskey="U">up</a> | <a href="class-based-views/index.html" title="Class-based views">next</a> »</div> </div> <div id="bd"> <div id="yui-main"> <div class="yui-b"> <div class="yui-g" id="topics-templates"> <div class="section" id="s-module-django.template"> <span id="s-templates"></span><span id="module-django.template"></span><span id="templates"></span><h1>Templates<a class="headerlink" href="#module-django.template" title="Permalink to this headline">¶</a></h1> <p>Being a web framework, Django needs a convenient way to generate HTML dynamically. The most common approach relies on templates. A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted. For a hands-on example of creating HTML pages with templates, see <a class="reference internal" href="../intro/tutorial03.html"><span class="doc">Tutorial 3</span></a>.</p> <p>A Django project can be configured with one or several template engines (or even zero if you don’t use templates). Django ships built-in backends for its own template system, creatively called the Django template language (DTL), and for the popular alternative <a class="reference external" href="http://jinja.pocoo.org/">Jinja2</a>. Backends for other template languages may be available from third-parties.</p> <p>Django defines a standard API for loading and rendering templates regardless of the backend. Loading consists of finding the template for a given identifier and preprocessing it, usually compiling it to an in-memory representation. Rendering means interpolating the template with context data and returning the resulting string.</p> <p>The <a class="reference internal" href="../ref/templates/language.html"><span class="doc">Django template language</span></a> is Django’s own template system. Until Django 1.8 it was the only built-in option available. It’s a good template library even though it’s fairly opinionated and sports a few idiosyncrasies. If you don’t have a pressing reason to choose another backend, you should use the DTL, especially if you’re writing a pluggable application and you intend to distribute templates. Django’s contrib apps that include templates, like <a class="reference internal" href="../ref/contrib/admin/index.html"><span class="doc">django.contrib.admin</span></a>, use the DTL.</p> <p>For historical reasons, both the generic support for template engines and the implementation of the Django template language live in the <code class="docutils literal"><span class="pre">django.template</span></code> namespace.</p> <div class="section" id="s-support-for-template-engines"> <span id="s-template-engines"></span><span id="support-for-template-engines"></span><span id="template-engines"></span><h2>Support for template engines<a class="headerlink" href="#support-for-template-engines" title="Permalink to this headline">¶</a></h2> <div class="versionadded"> <span class="title">New in Django 1.8:</span> <p>Support for multiple template engines and the <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES"><code class="xref std std-setting docutils literal"><span class="pre">TEMPLATES</span></code></a> setting were added in Django 1.8.</p> </div> <div class="section" id="s-configuration"> <span id="configuration"></span><h3>Configuration<a class="headerlink" href="#configuration" title="Permalink to this headline">¶</a></h3> <p>Templates engines are configured with the <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES"><code class="xref std std-setting docutils literal"><span class="pre">TEMPLATES</span></code></a> setting. It’s a list of configurations, one for each engine. The default value is empty. The <code class="docutils literal"><span class="pre">settings.py</span></code> generated by the <a class="reference internal" href="../ref/django-admin.html#django-admin-startproject"><code class="xref std std-djadmin docutils literal"><span class="pre">startproject</span></code></a> command defines a more useful value:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">TEMPLATES</span> <span class="o">=</span> <span class="p">[</span> <span class="p">{</span> <span class="s1">'BACKEND'</span><span class="p">:</span> <span class="s1">'django.template.backends.django.DjangoTemplates'</span><span class="p">,</span> <span class="s1">'DIRS'</span><span class="p">:</span> <span class="p">[],</span> <span class="s1">'APP_DIRS'</span><span class="p">:</span> <span class="kc">True</span><span class="p">,</span> <span class="s1">'OPTIONS'</span><span class="p">:</span> <span class="p">{</span> <span class="c1"># ... some options here ...</span> <span class="p">},</span> <span class="p">},</span> <span class="p">]</span> </pre></div> </div> <p><a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES-BACKEND"><code class="xref std std-setting docutils literal"><span class="pre">BACKEND</span></code></a> is a dotted Python path to a template engine class implementing Django’s template backend API. The built-in backends are <a class="reference internal" href="#django.template.backends.django.DjangoTemplates" title="django.template.backends.django.DjangoTemplates"><code class="xref py py-class docutils literal"><span class="pre">django.template.backends.django.DjangoTemplates</span></code></a> and <a class="reference internal" href="#django.template.backends.jinja2.Jinja2" title="django.template.backends.jinja2.Jinja2"><code class="xref py py-class docutils literal"><span class="pre">django.template.backends.jinja2.Jinja2</span></code></a>.</p> <p>Since most engines load templates from files, the top-level configuration for each engine contains two common settings:</p> <ul class="simple"> <li><a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES-DIRS"><code class="xref std std-setting docutils literal"><span class="pre">DIRS</span></code></a> defines a list of directories where the engine should look for template source files, in search order.</li> <li><a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES-APP_DIRS"><code class="xref std std-setting docutils literal"><span class="pre">APP_DIRS</span></code></a> tells whether the engine should look for templates inside installed applications. Each backend defines a conventional name for the subdirectory inside applications where its templates should be stored.</li> </ul> <p>While uncommon, it’s possible to configure several instances of the same backend with different options. In that case you should define a unique <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES-NAME"><code class="xref std std-setting docutils literal"><span class="pre">NAME</span></code></a> for each engine.</p> <p><a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES-OPTIONS"><code class="xref std std-setting docutils literal"><span class="pre">OPTIONS</span></code></a> contains backend-specific settings.</p> </div> <div class="section" id="s-usage"> <span id="usage"></span><h3>Usage<a class="headerlink" href="#usage" title="Permalink to this headline">¶</a></h3> <span class="target" id="module-django.template.loader"><span id="template-loading"></span></span><p>The <code class="docutils literal"><span class="pre">django.template.loader</span></code> module defines two functions to load templates.</p> <dl class="function"> <dt id="django.template.loader.get_template"> <code class="descname">get_template</code>(<em>template_name</em>, <em>dirs=_dirs_undefined</em>, <em>using=None</em>)<a class="reference internal" href="../_modules/django/template/loader.html#get_template"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.template.loader.get_template" title="Permalink to this definition">¶</a></dt> <dd><p>This function loads the template with the given name and returns a <code class="docutils literal"><span class="pre">Template</span></code> object.</p> <p>The exact type of the return value depends on the backend that loaded the template. Each backend has its own <code class="docutils literal"><span class="pre">Template</span></code> class.</p> <p><code class="docutils literal"><span class="pre">get_template()</span></code> tries each template engine in order until one succeeds. If the template cannot be found, it raises <a class="reference internal" href="#django.template.TemplateDoesNotExist" title="django.template.TemplateDoesNotExist"><code class="xref py py-exc docutils literal"><span class="pre">TemplateDoesNotExist</span></code></a>. If the template is found but contains invalid syntax, it raises <a class="reference internal" href="#django.template.TemplateSyntaxError" title="django.template.TemplateSyntaxError"><code class="xref py py-exc docutils literal"><span class="pre">TemplateSyntaxError</span></code></a>.</p> <p>How templates are searched and loaded depends on each engine’s backend and configuration.</p> <p>If you want to restrict the search to a particular template engine, pass the engine’s <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES-NAME"><code class="xref std std-setting docutils literal"><span class="pre">NAME</span></code></a> in the <code class="docutils literal"><span class="pre">using</span></code> argument.</p> <div class="versionchanged"> <span class="title">Changed in Django 1.7:</span> <p>The <code class="docutils literal"><span class="pre">dirs</span></code> parameter was added.</p> </div> <div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.8: </span>The <code class="docutils literal"><span class="pre">dirs</span></code> parameter was deprecated.</p> </div> <div class="versionchanged"> <span class="title">Changed in Django 1.8:</span> <p>The <code class="docutils literal"><span class="pre">using</span></code> parameter was added.</p> </div> <div class="versionchanged"> <span class="title">Changed in Django 1.8:</span> <p><code class="docutils literal"><span class="pre">get_template()</span></code> returns a backend-dependent <code class="docutils literal"><span class="pre">Template</span></code> instead of a <a class="reference internal" href="../ref/templates/api.html#django.template.Template" title="django.template.Template"><code class="xref py py-class docutils literal"><span class="pre">django.template.Template</span></code></a>.</p> </div> </dd></dl> <dl class="function"> <dt id="django.template.loader.select_template"> <code class="descname">select_template</code>(<em>template_name_list</em>, <em>dirs=_dirs_undefined</em>, <em>using=None</em>)<a class="reference internal" href="../_modules/django/template/loader.html#select_template"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.template.loader.select_template" title="Permalink to this definition">¶</a></dt> <dd><p><code class="docutils literal"><span class="pre">select_template()</span></code> is just like <code class="docutils literal"><span class="pre">get_template()</span></code>, except it takes a list of template names. It tries each name in order and returns the first template that exists.</p> <div class="versionchanged"> <span class="title">Changed in Django 1.7:</span> <p>The <code class="docutils literal"><span class="pre">dirs</span></code> parameter was added.</p> </div> <div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.8: </span>The <code class="docutils literal"><span class="pre">dirs</span></code> parameter was deprecated.</p> </div> <div class="versionchanged"> <span class="title">Changed in Django 1.8:</span> <p>The <code class="docutils literal"><span class="pre">using</span></code> parameter was added.</p> </div> <div class="versionchanged"> <span class="title">Changed in Django 1.8:</span> <p><code class="docutils literal"><span class="pre">select_template()</span></code> returns a backend-dependent <code class="docutils literal"><span class="pre">Template</span></code> instead of a <a class="reference internal" href="../ref/templates/api.html#django.template.Template" title="django.template.Template"><code class="xref py py-class docutils literal"><span class="pre">django.template.Template</span></code></a>.</p> </div> </dd></dl> <p>If loading a template fails, the following two exceptions, defined in <code class="docutils literal"><span class="pre">django.template</span></code>, may be raised:</p> <dl class="exception"> <dt id="django.template.TemplateDoesNotExist"> <em class="property">exception </em><code class="descname">TemplateDoesNotExist</code><a class="reference internal" href="../_modules/django/template/base.html#TemplateDoesNotExist"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.template.TemplateDoesNotExist" title="Permalink to this definition">¶</a></dt> <dd><p>This exception is raised when a template cannot be found.</p> </dd></dl> <dl class="exception"> <dt id="django.template.TemplateSyntaxError"> <em class="property">exception </em><code class="descname">TemplateSyntaxError</code><a class="reference internal" href="../_modules/django/template/base.html#TemplateSyntaxError"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.template.TemplateSyntaxError" title="Permalink to this definition">¶</a></dt> <dd><p>This exception is raised when a template was found but contains errors.</p> </dd></dl> <p><code class="docutils literal"><span class="pre">Template</span></code> objects returned by <code class="docutils literal"><span class="pre">get_template()</span></code> and <code class="docutils literal"><span class="pre">select_template()</span></code> must provide a <code class="docutils literal"><span class="pre">render()</span></code> method with the following signature:</p> <dl class="method"> <dt id="django.template.backends.base.Template.render"> <code class="descclassname">Template.</code><code class="descname">render</code>(<em>context=None</em>, <em>request=None</em>)<a class="headerlink" href="#django.template.backends.base.Template.render" title="Permalink to this definition">¶</a></dt> <dd><p>Renders this template with a given context.</p> <p>If <code class="docutils literal"><span class="pre">context</span></code> is provided, it must be a <code class="xref py py-class docutils literal"><span class="pre">dict</span></code>. If it isn’t provided, the engine will render the template with an empty context.</p> <p>If <code class="docutils literal"><span class="pre">request</span></code> is provided, it must be an <a class="reference internal" href="../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></code></a>. Then the engine must make it, as well as the CSRF token, available in the template. How this is achieved is up to each backend.</p> </dd></dl> <p>Here’s an example of the search algorithm. For this example the <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES"><code class="xref std std-setting docutils literal"><span class="pre">TEMPLATES</span></code></a> setting is:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">TEMPLATES</span> <span class="o">=</span> <span class="p">[</span> <span class="p">{</span> <span class="s1">'BACKEND'</span><span class="p">:</span> <span class="s1">'django.template.backends.django.DjangoTemplates'</span><span class="p">,</span> <span class="s1">'DIRS'</span><span class="p">:</span> <span class="p">[</span> <span class="s1">'/home/html/example.com'</span><span class="p">,</span> <span class="s1">'/home/html/default'</span><span class="p">,</span> <span class="p">],</span> <span class="p">},</span> <span class="p">{</span> <span class="s1">'BACKEND'</span><span class="p">:</span> <span class="s1">'django.template.backends.jinja2.Jinja2'</span><span class="p">,</span> <span class="s1">'DIRS'</span><span class="p">:</span> <span class="p">[</span> <span class="s1">'/home/html/jinja2'</span><span class="p">,</span> <span class="p">],</span> <span class="p">},</span> <span class="p">]</span> </pre></div> </div> <p>If you call <code class="docutils literal"><span class="pre">get_template('story_detail.html')</span></code>, here are the files Django will look for, in order:</p> <ul class="simple"> <li><code class="docutils literal"><span class="pre">/home/html/example.com/story_detail.html</span></code> (<code class="docutils literal"><span class="pre">'django'</span></code> engine)</li> <li><code class="docutils literal"><span class="pre">/home/html/default/story_detail.html</span></code> (<code class="docutils literal"><span class="pre">'django'</span></code> engine)</li> <li><code class="docutils literal"><span class="pre">/home/html/jinja2/story_detail.html</span></code> (<code class="docutils literal"><span class="pre">'jinja2'</span></code> engine)</li> </ul> <p>If you call <code class="docutils literal"><span class="pre">select_template(['story_253_detail.html',</span> <span class="pre">'story_detail.html'])</span></code>, here’s what Django will look for:</p> <ul class="simple"> <li><code class="docutils literal"><span class="pre">/home/html/example.com/story_253_detail.html</span></code> (<code class="docutils literal"><span class="pre">'django'</span></code> engine)</li> <li><code class="docutils literal"><span class="pre">/home/html/default/story_253_detail.html</span></code> (<code class="docutils literal"><span class="pre">'django'</span></code> engine)</li> <li><code class="docutils literal"><span class="pre">/home/html/jinja2/story_253_detail.html</span></code> (<code class="docutils literal"><span class="pre">'jinja2'</span></code> engine)</li> <li><code class="docutils literal"><span class="pre">/home/html/example.com/story_detail.html</span></code> (<code class="docutils literal"><span class="pre">'django'</span></code> engine)</li> <li><code class="docutils literal"><span class="pre">/home/html/default/story_detail.html</span></code> (<code class="docutils literal"><span class="pre">'django'</span></code> engine)</li> <li><code class="docutils literal"><span class="pre">/home/html/jinja2/story_detail.html</span></code> (<code class="docutils literal"><span class="pre">'jinja2'</span></code> engine)</li> </ul> <p>When Django finds a template that exists, it stops looking.</p> <div class="admonition-tip admonition"> <p class="first admonition-title">Tip</p> <p class="last">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"><span class="pre">select_template()</span></code></a> for flexible template loading. For example, if you’ve written a news story and want some stories to have custom templates, use something like <code class="docutils literal"><span class="pre">select_template(['story_%s_detail.html'</span> <span class="pre">%</span> <span class="pre">story.id,</span> <span class="pre">'story_detail.html'])</span></code>. That’ll allow you to use a custom template for an individual story, with a fallback template for stories that don’t have custom templates.</p> </div> <p>It’s possible – and preferable – to organize templates in subdirectories inside each directory containing templates. The convention is to make a subdirectory for each Django app, with subdirectories within those subdirectories as needed.</p> <p>Do this for your own sanity. Storing all templates in the root level of a single directory gets messy.</p> <p>To load a template that’s within a subdirectory, just use a slash, like so:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="n">get_template</span><span class="p">(</span><span class="s1">'news/story_detail.html'</span><span class="p">)</span> </pre></div> </div> <p>Using the same <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES"><code class="xref std std-setting docutils literal"><span class="pre">TEMPLATES</span></code></a> option as above, this will attempt to load the following templates:</p> <ul class="simple"> <li><code class="docutils literal"><span class="pre">/home/html/example.com/news/story_detail.html</span></code> (<code class="docutils literal"><span class="pre">'django'</span></code> engine)</li> <li><code class="docutils literal"><span class="pre">/home/html/default/news/story_detail.html</span></code> (<code class="docutils literal"><span class="pre">'django'</span></code> engine)</li> <li><code class="docutils literal"><span class="pre">/home/html/jinja2/news/story_detail.html</span></code> (<code class="docutils literal"><span class="pre">'jinja2'</span></code> engine)</li> </ul> <p>In addition, to cut down on the repetitive nature of loading and rendering templates, Django provides a shortcut function which automates the process.</p> <dl class="function"> <dt id="django.template.loader.render_to_string"> <code class="descname">render_to_string</code>(<em>template_name</em>, <em>context=None</em>, <em>context_instance=_context_instance_undefined</em>, <em>request=None</em>, <em>using=None</em>)<a class="reference internal" href="../_modules/django/template/loader.html#render_to_string"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.template.loader.render_to_string" title="Permalink to this definition">¶</a></dt> <dd><p><code class="docutils literal"><span class="pre">render_to_string()</span></code> loads a template like <a class="reference internal" href="#django.template.loader.get_template" title="django.template.loader.get_template"><code class="xref py py-func docutils literal"><span class="pre">get_template()</span></code></a> and calls its <code class="docutils literal"><span class="pre">render()</span></code> method immediately. It takes the following arguments.</p> <dl class="docutils"> <dt><code class="docutils literal"><span class="pre">template_name</span></code></dt> <dd>The name of the template to load and render. If it’s a list of template names, Django uses <a class="reference internal" href="#django.template.loader.select_template" title="django.template.loader.select_template"><code class="xref py py-func docutils literal"><span class="pre">select_template()</span></code></a> instead of <a class="reference internal" href="#django.template.loader.get_template" title="django.template.loader.get_template"><code class="xref py py-func docutils literal"><span class="pre">get_template()</span></code></a> to find the template.</dd> <dt><code class="docutils literal"><span class="pre">context</span></code></dt> <dd><p class="first">A <code class="xref py py-class docutils literal"><span class="pre">dict</span></code> to be used as the template’s context for rendering.</p> <div class="last versionchanged"> <span class="title">Changed in Django 1.8:</span> <p>The <code class="docutils literal"><span class="pre">context</span></code> argument used to be called <code class="docutils literal"><span class="pre">dictionary</span></code>. That name is deprecated in Django 1.8 and will be removed in Django 1.10.</p> <p><code class="docutils literal"><span class="pre">context</span></code> is now optional. An empty context will be used if it isn’t provided.</p> </div> </dd> <dt><code class="docutils literal"><span class="pre">context_instance</span></code></dt> <dd><p class="first">An instance of <a class="reference internal" href="../ref/templates/api.html#django.template.Context" title="django.template.Context"><code class="xref py py-class docutils literal"><span class="pre">Context</span></code></a> or a subclass (e.g., an instance of <a class="reference internal" href="../ref/templates/api.html#django.template.RequestContext" title="django.template.RequestContext"><code class="xref py py-class docutils literal"><span class="pre">RequestContext</span></code></a>) to use as the template’s context.</p> <div class="last deprecated"> <p><span class="versionmodified">Deprecated since version 1.8: </span>The <code class="docutils literal"><span class="pre">context_instance</span></code> argument is deprecated. Use <code class="docutils literal"><span class="pre">context</span></code> and if needed <code class="docutils literal"><span class="pre">request</span></code>.</p> </div> </dd> <dt><code class="docutils literal"><span class="pre">request</span></code></dt> <dd><p class="first">An optional <a class="reference internal" href="../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></code></a> that will be available during the template’s rendering process.</p> <div class="last versionadded"> <span class="title">New in Django 1.8:</span> <p>The <code class="docutils literal"><span class="pre">request</span></code> argument was added.</p> </div> </dd> </dl> </dd></dl> <p>See also the <a class="reference internal" href="http/shortcuts.html#django.shortcuts.render" title="django.shortcuts.render"><code class="xref py py-func docutils literal"><span class="pre">render()</span></code></a> and <a class="reference internal" href="http/shortcuts.html#django.shortcuts.render_to_response" title="django.shortcuts.render_to_response"><code class="xref py py-func docutils literal"><span class="pre">render_to_response()</span></code></a> shortcuts, which call <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"><span class="pre">render_to_string()</span></code></a> and feed the result into an <a class="reference internal" href="../ref/request-response.html#django.http.HttpResponse" title="django.http.HttpResponse"><code class="xref py py-class docutils literal"><span class="pre">HttpResponse</span></code></a> suitable for returning from a view.</p> <p>Finally, you can use configured engines directly:</p> <dl class="data"> <dt id="django.template.loader.engines"> <code class="descname">engines</code><a class="headerlink" href="#django.template.loader.engines" title="Permalink to this definition">¶</a></dt> <dd><p>Template engines are available in <code class="docutils literal"><span class="pre">django.template.engines</span></code>:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.template</span> <span class="k">import</span> <span class="n">engines</span> <span class="n">django_engine</span> <span class="o">=</span> <span class="n">engines</span><span class="p">[</span><span class="s1">'django'</span><span class="p">]</span> <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">"Hello {{ name }}!"</span><span class="p">)</span> </pre></div> </div> <p>The lookup key — <code class="docutils literal"><span class="pre">'django'</span></code> in this example — is the engine’s <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES-NAME"><code class="xref std std-setting docutils literal"><span class="pre">NAME</span></code></a>.</p> </dd></dl> <span class="target" id="module-django.template.backends"></span></div> <div class="section" id="s-module-django.template.backends.django"> <span id="s-built-in-backends"></span><span id="module-django.template.backends.django"></span><span id="built-in-backends"></span><h3>Built-in backends<a class="headerlink" href="#module-django.template.backends.django" title="Permalink to this headline">¶</a></h3> <dl class="class"> <dt id="django.template.backends.django.DjangoTemplates"> <em class="property">class </em><code class="descname">DjangoTemplates</code><a class="reference internal" href="../_modules/django/template/backends/django.html#DjangoTemplates"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#django.template.backends.django.DjangoTemplates" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Set <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES-BACKEND"><code class="xref std std-setting docutils literal"><span class="pre">BACKEND</span></code></a> to <code class="docutils literal"><span class="pre">'django.template.backends.django.DjangoTemplates'</span></code> to configure a Django template engine.</p> <p>When <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES-APP_DIRS"><code class="xref std std-setting docutils literal"><span class="pre">APP_DIRS</span></code></a> is <code class="docutils literal"><span class="pre">True</span></code>, <code class="docutils literal"><span class="pre">DjangoTemplates</span></code> engines look for templates in the <code class="docutils literal"><span class="pre">templates</span></code> subdirectory of installed applications. This generic name was kept for backwards-compatibility.</p> <p><code class="docutils literal"><span class="pre">DjangoTemplates</span></code> engines accept the following <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES-OPTIONS"><code class="xref std std-setting docutils literal"><span class="pre">OPTIONS</span></code></a>:</p> <ul> <li><p class="first"><code class="docutils literal"><span class="pre">'allowed_include_roots'</span></code>: a list of strings representing allowed prefixes for the <code class="docutils literal"><span class="pre">{%</span> <span class="pre">ssi</span> <span class="pre">%}</span></code> template tag. This is a security measure, so that template authors can’t access files that they shouldn’t be accessing.</p> <p>For example, if <code class="docutils literal"><span class="pre">'allowed_include_roots'</span></code> is <code class="docutils literal"><span class="pre">['/home/html',</span> <span class="pre">'/var/www']</span></code>, then <code class="docutils literal"><span class="pre">{%</span> <span class="pre">ssi</span> <span class="pre">/home/html/foo.txt</span> <span class="pre">%}</span></code> would work, but <code class="docutils literal"><span class="pre">{%</span> <span class="pre">ssi</span> <span class="pre">/etc/passwd</span> <span class="pre">%}</span></code> wouldn’t.</p> <p>It defaults to an empty list.</p> <div class="deprecated"> <p><span class="versionmodified">Deprecated since version 1.8: </span><code class="docutils literal"><span class="pre">allowed_include_roots</span></code> is deprecated because the {% ssi %} tag is deprecated.</p> </div> </li> <li><p class="first"><code class="docutils literal"><span class="pre">'context_processors'</span></code>: a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request. These callables take a request object as their argument and return a <code class="xref py py-class docutils literal"><span class="pre">dict</span></code> of items to be merged into the context.</p> <p>It defaults to an empty list.</p> <p>See <a class="reference internal" href="../ref/templates/api.html#django.template.RequestContext" title="django.template.RequestContext"><code class="xref py py-class docutils literal"><span class="pre">RequestContext</span></code></a> for more information.</p> </li> <li><p class="first"><code class="docutils literal"><span class="pre">'debug'</span></code>: a boolean that turns on/off template debug mode. If it is <code class="docutils literal"><span class="pre">True</span></code>, the fancy error page will display a detailed report for any exception raised during template rendering. This report contains the relevant snippet of the template with the appropriate line highlighted.</p> <p>It defaults to the value of the <a class="reference internal" href="../ref/settings.html#std:setting-DEBUG"><code class="xref std std-setting docutils literal"><span class="pre">DEBUG</span></code></a> setting.</p> </li> <li><p class="first"><code class="docutils literal"><span class="pre">'loaders'</span></code>: a list of dotted Python paths to template loader classes. Each <code class="docutils literal"><span class="pre">Loader</span></code> class knows how to import templates from a particular source. Optionally, a tuple can be used instead of a string. The first item in the tuple should be the <code class="docutils literal"><span class="pre">Loader</span></code> class name, and subsequent items are passed to the <code class="docutils literal"><span class="pre">Loader</span></code> during initialization.</p> <p>The default depends on the values of <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES-DIRS"><code class="xref std std-setting docutils literal"><span class="pre">DIRS</span></code></a> and <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES-APP_DIRS"><code class="xref std std-setting docutils literal"><span class="pre">APP_DIRS</span></code></a>.</p> <p>See <a class="reference internal" href="../ref/templates/api.html#template-loaders"><span class="std std-ref">Loader types</span></a> for details.</p> </li> <li><p class="first"><code class="docutils literal"><span class="pre">'string_if_invalid'</span></code>: the output, as a string, that the template system should use for invalid (e.g. misspelled) variables.</p> <p>It defaults to an empty string.</p> <p>See <a class="reference internal" href="../ref/templates/api.html#invalid-template-variables"><span class="std std-ref">How invalid variables are handled</span></a> for details.</p> </li> <li><p class="first"><code class="docutils literal"><span class="pre">'file_charset'</span></code>: the charset used to read template files on disk.</p> <p>It defaults to the value of <a class="reference internal" href="../ref/settings.html#std:setting-FILE_CHARSET"><code class="xref std std-setting docutils literal"><span class="pre">FILE_CHARSET</span></code></a>.</p> </li> </ul> <span class="target" id="module-django.template.backends.jinja2"></span><dl class="class"> <dt id="django.template.backends.jinja2.Jinja2"> <em class="property">class </em><code class="descname">Jinja2</code><a class="headerlink" href="#django.template.backends.jinja2.Jinja2" title="Permalink to this definition">¶</a></dt> <dd></dd></dl> <p>Requires <a class="reference external" href="http://jinja.pocoo.org/">Jinja2</a> to be installed:</p> <div class="highlight-console"><div class="highlight"><pre><span></span><span class="gp">$</span> pip install Jinja2 </pre></div> </div> <p>Set <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES-BACKEND"><code class="xref std std-setting docutils literal"><span class="pre">BACKEND</span></code></a> to <code class="docutils literal"><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> <p>When <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES-APP_DIRS"><code class="xref std std-setting docutils literal"><span class="pre">APP_DIRS</span></code></a> is <code class="docutils literal"><span class="pre">True</span></code>, <code class="docutils literal"><span class="pre">Jinja2</span></code> engines look for templates in the <code class="docutils literal"><span class="pre">jinja2</span></code> subdirectory of installed applications.</p> <p>The most important entry in <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES-OPTIONS"><code class="xref std std-setting docutils literal"><span class="pre">OPTIONS</span></code></a> is <code class="docutils literal"><span class="pre">'environment'</span></code>. It’s a dotted Python path to a callable returning a Jinja2 environment. It defaults to <code class="docutils literal"><span class="pre">'jinja2.Environment'</span></code>. Django invokes that callable and passes other options as keyword arguments. Furthermore, Django adds defaults that differ from Jinja2’s for a few options:</p> <ul class="simple"> <li><code class="docutils literal"><span class="pre">'autoescape'</span></code>: <code class="docutils literal"><span class="pre">True</span></code></li> <li><code class="docutils literal"><span class="pre">'loader'</span></code>: a loader configured for <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES-DIRS"><code class="xref std std-setting docutils literal"><span class="pre">DIRS</span></code></a> and <a class="reference internal" href="../ref/settings.html#std:setting-TEMPLATES-APP_DIRS"><code class="xref std std-setting docutils literal"><span class="pre">APP_DIRS</span></code></a></li> <li><code class="docutils literal"><span class="pre">'auto_reload'</span></code>: <code class="docutils literal"><span class="pre">settings.DEBUG</span></code></li> <li><code class="docutils literal"><span class="pre">'undefined'</span></code>: <code class="docutils literal"><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></li> </ul> <p>The default configuration is purposefully kept to a minimum. The <code class="docutils literal"><span class="pre">Jinja2</span></code> backend doesn’t create a Django-flavored environment. It doesn’t know about Django context processors, filters, and tags. In order to use Django-specific APIs, you must configure them into the environment.</p> <p>For example, you can create <code class="docutils literal"><span class="pre">myproject/jinja2.py</span></code> with this content:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">__future__</span> <span class="k">import</span> <span class="n">absolute_import</span> <span class="c1"># Python 2 only</span> <span class="kn">from</span> <span class="nn">django.contrib.staticfiles.storage</span> <span class="k">import</span> <span class="n">staticfiles_storage</span> <span class="kn">from</span> <span class="nn">django.core.urlresolvers</span> <span class="k">import</span> <span class="n">reverse</span> <span class="kn">from</span> <span class="nn">jinja2</span> <span class="k">import</span> <span class="n">Environment</span> <span class="k">def</span> <span class="nf">environment</span><span class="p">(</span><span class="o">**</span><span class="n">options</span><span class="p">):</span> <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> <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> <span class="s1">'static'</span><span class="p">:</span> <span class="n">staticfiles_storage</span><span class="o">.</span><span class="n">url</span><span class="p">,</span> <span class="s1">'url'</span><span class="p">:</span> <span class="n">reverse</span><span class="p">,</span> <span class="p">})</span> <span class="k">return</span> <span class="n">env</span> </pre></div> </div> <p>and set the <code class="docutils literal"><span class="pre">'environment'</span></code> option to <code class="docutils literal"><span class="pre">'myproject.jinja2.environment'</span></code>.</p> <p>Then you could use the following constructs in Jinja2 templates:</p> <div class="highlight-html+jinja"><div class="highlight"><pre><span></span><span class="p"><</span><span class="nt">img</span> <span class="na">src</span><span class="o">=</span><span class="s">"</span><span class="cp">{{</span> <span class="nv">static</span><span class="o">(</span><span class="s1">'path/to/company-logo.png'</span><span class="o">)</span> <span class="cp">}}</span><span class="s">"</span> <span class="na">alt</span><span class="o">=</span><span class="s">"Company Logo"</span><span class="p">></span> <span class="p"><</span><span class="nt">a</span> <span class="na">href</span><span class="o">=</span><span class="s">"</span><span class="cp">{{</span> <span class="nv">url</span><span class="o">(</span><span class="s1">'admin:index'</span><span class="o">)</span> <span class="cp">}}</span><span class="s">"</span><span class="p">></span>Administration<span class="p"></</span><span class="nt">a</span><span class="p">></span> </pre></div> </div> <p>The concepts of tags and filters exist both in the Django template language and in Jinja2 but they’re used differently. Since Jinja2 supports passing arguments to callables in templates, many features that require a template tag or filter in Django templates can be achieved simply by calling a function in Jinja2 templates, as shown in the example above. Jinja2’s global namespace removes the need for template context processors. The Django template language doesn’t have an equivalent of Jinja2 tests.</p> </div> <div class="section" id="s-custom-backends"> <span id="custom-backends"></span><h3>Custom backends<a class="headerlink" href="#custom-backends" title="Permalink to this headline">¶</a></h3> <p>Here’s how to implement a custom template backend in order to use another template system. A template backend is a class that inherits <code class="docutils literal"><span class="pre">django.template.backends.base.BaseEngine</span></code>. It must implement <code class="docutils literal"><span class="pre">get_template()</span></code> and optionally <code class="docutils literal"><span class="pre">from_string()</span></code>. Here’s an example for a fictional <code class="docutils literal"><span class="pre">foobar</span></code> template library:</p> <div class="highlight-default"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.template</span> <span class="k">import</span> <span class="n">TemplateDoesNotExist</span><span class="p">,</span> <span class="n">TemplateSyntaxError</span> <span class="kn">from</span> <span class="nn">django.template.backends.base</span> <span class="k">import</span> <span class="n">BaseEngine</span> <span class="kn">from</span> <span class="nn">django.template.backends.utils</span> <span class="k">import</span> <span class="n">csrf_input_lazy</span><span class="p">,</span> <span class="n">csrf_token_lazy</span> <span class="kn">import</span> <span class="nn">foobar</span> <span class="k">class</span> <span class="nc">FooBar</span><span class="p">(</span><span class="n">BaseEngine</span><span class="p">):</span> <span class="c1"># Name of the subdirectory containing the templates for this engine</span> <span class="c1"># inside an installed application.</span> <span class="n">app_dirname</span> <span class="o">=</span> <span class="s1">'foobar'</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">params</span><span class="p">):</span> <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> <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">'OPTIONS'</span><span class="p">)</span><span class="o">.</span><span class="n">copy</span><span class="p">()</span> <span class="nb">super</span><span class="p">(</span><span class="n">FooBar</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="n">params</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">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> <span class="k">def</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> <span class="k">try</span><span class="p">:</span> <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> <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> <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> <span class="k">def</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> <span class="k">try</span><span class="p">:</span> <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> <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> <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="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> <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> <span class="k">class</span> <span class="nc">Template</span><span class="p">(</span><span class="nb">object</span><span class="p">):</span> <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">template</span><span class="p">):</span> <span class="bp">self</span><span class="o">.</span><span class="n">template</span> <span class="o">=</span> <span class="n">template</span> <span class="k">def</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> <span class="k">if</span> <span class="n">context</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span> <span class="n">context</span> <span class="o">=</span> <span class="p">{}</span> <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> <span class="n">context</span><span class="p">[</span><span class="s1">'request'</span><span class="p">]</span> <span class="o">=</span> <span class="n">request</span> <span class="n">context</span><span class="p">[</span><span class="s1">'csrf_input'</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> <span class="n">context</span><span class="p">[</span><span class="s1">'csrf_token'</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> <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> </pre></div> </div> <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> </div> </div> <div class="section" id="s-the-django-template-language"> <span id="s-template-language-intro"></span><span id="the-django-template-language"></span><span id="template-language-intro"></span><h2>The Django template language<a class="headerlink" href="#the-django-template-language" title="Permalink to this headline">¶</a></h2> <div class="section" id="s-syntax"> <span id="syntax"></span><h3>Syntax<a class="headerlink" href="#syntax" title="Permalink to this headline">¶</a></h3> <div class="admonition-about-this-section admonition"> <p class="first admonition-title">About this section</p> <p class="last">This is an overview of the Django template language’s syntax. For details see the <a class="reference internal" href="../ref/templates/language.html"><span class="doc">language syntax reference</span></a>.</p> </div> <p>A Django template is simply a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags.</p> <p>A template is rendered with a context. Rendering replaces variables with their values, which are looked up in the context, and executes tags. Everything else is output as is.</p> <p>The syntax of the Django template language involves four constructs.</p> <div class="section" id="s-variables"> <span id="variables"></span><h4>Variables<a class="headerlink" href="#variables" title="Permalink to this headline">¶</a></h4> <p>A variable outputs a value from the context, which is a dict-like object mapping keys to values.</p> <p>Variables are surrounded by <code class="docutils literal"><span class="pre">{{</span></code> and <code class="docutils literal"><span class="pre">}}</span></code> like this:</p> <div class="highlight-html+django"><div class="highlight"><pre><span></span>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>. </pre></div> </div> <p>With a context of <code class="docutils literal"><span class="pre">{'first_name':</span> <span class="pre">'John',</span> <span class="pre">'last_name':</span> <span class="pre">'Doe'}</span></code>, this template renders to:</p> <div class="highlight-html+django"><div class="highlight"><pre><span></span>My first name is John. My last name is Doe. </pre></div> </div> <p>Dictionary lookup, attribute lookup and list-index lookups are implemented with a dot notation:</p> <div class="highlight-html+django"><div class="highlight"><pre><span></span><span class="cp">{{</span> <span class="nv">my_dict.key</span> <span class="cp">}}</span> <span class="cp">{{</span> <span class="nv">my_object.attribute</span> <span class="cp">}}</span> <span class="cp">{{</span> <span class="nv">my_list.0</span> <span class="cp">}}</span> </pre></div> </div> <p>If a variable resolves to a callable, the template system will call it with no arguments and use its result instead of the callable.</p> </div> <div class="section" id="s-tags"> <span id="tags"></span><h4>Tags<a class="headerlink" href="#tags" title="Permalink to this headline">¶</a></h4> <p>Tags provide arbitrary logic in the rendering process.</p> <p>This definition is deliberately vague. For example, a tag can output content, serve as a control structure e.g. an “if” statement or a “for” loop, grab content from a database, or even enable access to other template tags.</p> <p>Tags are surrounded by <code class="docutils literal"><span class="pre">{%</span></code> and <code class="docutils literal"><span class="pre">%}</span></code> like this:</p> <div class="highlight-html+django"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">csrf_token</span> <span class="cp">%}</span> </pre></div> </div> <p>Most tags accept arguments:</p> <div class="highlight-html+django"><div class="highlight"><pre><span></span><span class="cp">{%</span> <span class="k">cycle</span> <span class="s1">'odd'</span> <span class="s1">'even'</span> <span class="cp">%}</span> </pre></div> </div> <p>Some tags require beginning and ending tags:</p> <div class="highlight-html+django"><div class="highlight"><pre><span></span><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> </pre></div> </div> <p>A <a class="reference internal" href="../ref/templates/builtins.html#ref-templates-builtins-tags"><span class="std std-ref">reference of built-in tags</span></a> is available as well as <a class="reference internal" href="../howto/custom-template-tags.html#howto-writing-custom-template-tags"><span class="std std-ref">instructions for writing custom tags</span></a>.</p> </div> <div class="section" id="s-filters"> <span id="filters"></span><h4>Filters<a class="headerlink" href="#filters" title="Permalink to this headline">¶</a></h4> <p>Filters transform the values of variables and tag arguments.</p> <p>They look like this:</p> <div class="highlight-html+django"><div class="highlight"><pre><span></span><span class="cp">{{</span> <span class="nv">django</span><span class="o">|</span><span class="nf">title</span> <span class="cp">}}</span> </pre></div> </div> <p>With a context of <code class="docutils literal"><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> <span class="pre">deadlines'}</span></code>, this template renders to:</p> <div class="highlight-html+django"><div class="highlight"><pre><span></span>The Web Framework For Perfectionists With Deadlines </pre></div> </div> <p>Some filters take an argument:</p> <div class="highlight-html+django"><div class="highlight"><pre><span></span><span class="cp">{{</span> <span class="nv">my_date</span><span class="o">|</span><span class="nf">date</span><span class="s2">:"Y-m-d"</span> <span class="cp">}}</span> </pre></div> </div> <p>A <a class="reference internal" href="../ref/templates/builtins.html#ref-templates-builtins-filters"><span class="std std-ref">reference of built-in filters</span></a> is available as well as <a class="reference internal" href="../howto/custom-template-tags.html#howto-writing-custom-template-filters"><span class="std std-ref">instructions for writing custom filters</span></a>.</p> </div> <div class="section" id="s-comments"> <span id="comments"></span><h4>Comments<a class="headerlink" href="#comments" title="Permalink to this headline">¶</a></h4> <p>Comments look like this:</p> <div class="highlight-html+django"><div class="highlight"><pre><span></span><span class="c">{# this won't be rendered #}</span> </pre></div> </div> <p>A <a class="reference internal" href="../ref/templates/builtins.html#std:templatetag-comment"><code class="xref std std-ttag docutils literal"><span class="pre">{%</span> <span class="pre">comment</span> <span class="pre">%}</span></code></a> tag provides multi-line comments.</p> </div> </div> <div class="section" id="s-components"> <span id="components"></span><h3>Components<a class="headerlink" href="#components" title="Permalink to this headline">¶</a></h3> <div class="admonition-about-this-section admonition"> <p class="first admonition-title">About this section</p> <p class="last">This is an overview of the Django template language’s APIs. For details see the <a class="reference internal" href="../ref/templates/api.html"><span class="doc">API reference</span></a>.</p> </div> <div class="section" id="s-engine"> <span id="engine"></span><h4>Engine<a class="headerlink" href="#engine" title="Permalink to this headline">¶</a></h4> <p><a class="reference internal" href="../ref/templates/api.html#django.template.Engine" title="django.template.Engine"><code class="xref py py-class docutils literal"><span class="pre">django.template.Engine</span></code></a> encapsulates an instance of the Django template system. The main reason for instantiating an <a class="reference internal" href="../ref/templates/api.html#django.template.Engine" title="django.template.Engine"><code class="xref py py-class docutils literal"><span class="pre">Engine</span></code></a> directly is to use the Django template language outside of a Django project.</p> <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"><span class="pre">django.template.backends.django.DjangoTemplates</span></code></a> is a thin wrapper adapting <a class="reference internal" href="../ref/templates/api.html#django.template.Engine" title="django.template.Engine"><code class="xref py py-class docutils literal"><span class="pre">django.template.Engine</span></code></a> to Django’s template backend API.</p> </div> <div class="section" id="s-template"> <span id="template"></span><h4>Template<a class="headerlink" href="#template" title="Permalink to this headline">¶</a></h4> <p><a class="reference internal" href="../ref/templates/api.html#django.template.Template" title="django.template.Template"><code class="xref py py-class docutils literal"><span class="pre">django.template.Template</span></code></a> represents a compiled template. Templates are obtained with <a class="reference internal" href="../ref/templates/api.html#django.template.Engine.get_template" title="django.template.Engine.get_template"><code class="xref py py-meth docutils literal"><span class="pre">Engine.get_template()</span></code></a> or <a class="reference internal" href="../ref/templates/api.html#django.template.Engine.from_string" title="django.template.Engine.from_string"><code class="xref py py-meth docutils literal"><span class="pre">Engine.from_string()</span></code></a></p> <p>Likewise <code class="docutils literal"><span class="pre">django.template.backends.django.Template</span></code> is a thin wrapper adapting <a class="reference internal" href="../ref/templates/api.html#django.template.Template" title="django.template.Template"><code class="xref py py-class docutils literal"><span class="pre">django.template.Template</span></code></a> to the common template API.</p> </div> <div class="section" id="s-context"> <span id="context"></span><h4>Context<a class="headerlink" href="#context" title="Permalink to this headline">¶</a></h4> <p><a class="reference internal" href="../ref/templates/api.html#django.template.Context" title="django.template.Context"><code class="xref py py-class docutils literal"><span class="pre">django.template.Context</span></code></a> holds some metadata in addition to the context data. It is passed to <a class="reference internal" href="../ref/templates/api.html#django.template.Template.render" title="django.template.Template.render"><code class="xref py py-meth docutils literal"><span class="pre">Template.render()</span></code></a> for rendering a template.</p> <p><a class="reference internal" href="../ref/templates/api.html#django.template.RequestContext" title="django.template.RequestContext"><code class="xref py py-class docutils literal"><span class="pre">django.template.RequestContext</span></code></a> is a subclass of <a class="reference internal" href="../ref/templates/api.html#django.template.Context" title="django.template.Context"><code class="xref py py-class docutils literal"><span class="pre">Context</span></code></a> that stores the current <a class="reference internal" href="../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></code></a> and runs template context processors.</p> <p>The common API doesn’t have an equivalent concept. Context data is passed in a plain <code class="xref py py-class docutils literal"><span class="pre">dict</span></code> and the current <a class="reference internal" href="../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></code></a> is passed separately if needed.</p> </div> <div class="section" id="s-loaders"> <span id="loaders"></span><h4>Loaders<a class="headerlink" href="#loaders" title="Permalink to this headline">¶</a></h4> <p>Template loaders are responsible for locating templates, loading them, and returning <a class="reference internal" href="../ref/templates/api.html#django.template.Template" title="django.template.Template"><code class="xref py py-class docutils literal"><span class="pre">Template</span></code></a> objects.</p> <p>Django provides several <a class="reference internal" href="../ref/templates/api.html#template-loaders"><span class="std std-ref">built-in template loaders</span></a> and supports <a class="reference internal" href="../ref/templates/api.html#custom-template-loaders"><span class="std std-ref">custom template loaders</span></a>.</p> </div> <div class="section" id="s-context-processors"> <span id="context-processors"></span><h4>Context processors<a class="headerlink" href="#context-processors" title="Permalink to this headline">¶</a></h4> <p>Context processors are functions that receive the current <a class="reference internal" href="../ref/request-response.html#django.http.HttpRequest" title="django.http.HttpRequest"><code class="xref py py-class docutils literal"><span class="pre">HttpRequest</span></code></a> as an argument and return a <code class="xref py py-class docutils literal"><span class="pre">dict</span></code> of data to be added to the rendering context.</p> <p>Their main use is to add common data shared by all templates to the context without repeating code in every view.</p> <p>Django provides many <a class="reference internal" href="../ref/templates/api.html#context-processors"><span class="std std-ref">built-in context processors</span></a>. Implementing a custom context processor is as simple as defining a function.</p> </div> </div> </div> </div> </div> </div> </div> <div class="yui-b" id="sidebar"> <div class="sphinxsidebar" role="navigation" aria-label="main navigation"> <div class="sphinxsidebarwrapper"> <h3><a href="../contents.html">Table Of Contents</a></h3> <ul> <li><a class="reference internal" href="#">Templates</a><ul> <li><a class="reference internal" href="#support-for-template-engines">Support for template engines</a><ul> <li><a class="reference internal" href="#configuration">Configuration</a></li> <li><a class="reference internal" href="#usage">Usage</a></li> <li><a class="reference internal" href="#module-django.template.backends.django">Built-in backends</a></li> <li><a class="reference internal" href="#custom-backends">Custom backends</a></li> </ul> </li> <li><a class="reference internal" href="#the-django-template-language">The Django template language</a><ul> <li><a class="reference internal" href="#syntax">Syntax</a><ul> <li><a class="reference internal" href="#variables">Variables</a></li> <li><a class="reference internal" href="#tags">Tags</a></li> <li><a class="reference internal" href="#filters">Filters</a></li> <li><a class="reference internal" href="#comments">Comments</a></li> </ul> </li> <li><a class="reference internal" href="#components">Components</a><ul> <li><a class="reference internal" href="#engine">Engine</a></li> <li><a class="reference internal" href="#template">Template</a></li> <li><a class="reference internal" href="#context">Context</a></li> <li><a class="reference internal" href="#loaders">Loaders</a></li> <li><a class="reference internal" href="#context-processors">Context processors</a></li> </ul> </li> </ul> </li> </ul> </li> </ul> <h3>Browse</h3> <ul> <li>Prev: <a href="forms/media.html">Form Assets (the <code class="docutils literal"><span class="pre">Media</span></code> class)</a></li> <li>Next: <a href="class-based-views/index.html">Class-based views</a></li> </ul> <h3>You are here:</h3> <ul> <li> <a href="../index.html">Django 1.8.19 documentation</a> <ul><li><a href="index.html">Using Django</a> <ul><li>Templates</li></ul> </li></ul> </li> </ul> <div role="note" aria-label="source link"> <h3>This Page</h3> <ul class="this-page-menu"> <li><a href="../_sources/topics/templates.txt" rel="nofollow">Show Source</a></li> </ul> </div> <div id="searchbox" style="display: none" role="search"> <h3>Quick search</h3> <form class="search" action="../search.html" method="get"> <div><input type="text" name="q" /></div> <div><input type="submit" value="Go" /></div> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <h3>Last update:</h3> <p class="topless">Jan 06, 2019</p> </div> </div> <div id="ft"> <div class="nav"> « <a href="forms/media.html" title="Form Assets (the <code class="docutils literal"><span class="pre">Media</span></code> class)">previous</a> | <a href="index.html" title="Using Django" accesskey="U">up</a> | <a href="class-based-views/index.html" title="Class-based views">next</a> »</div> </div> </div> <div class="clearer"></div> </div> </body> </html>