Sophie

Sophie

distrib > Mandriva > current > i586 > media > main-updates > by-pkgid > 57efe471f3561e70a829edf1b0e9f507 > files > 2235

python-django-1.1.4-0.1mdv2010.2.noarch.rpm

<!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">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Custom template tags and filters &mdash; Django v1.1 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.1',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="top" title="Django v1.1 documentation" href="../index.html" />
    <link rel="up" title="“How-to” guides" href="index.html" />
    <link rel="next" title="Writing a custom storage system" href="custom-file-storage.html" />
    <link rel="prev" title="Writing custom model fields" href="custom-model-fields.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>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django v1.1 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="../modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="custom-model-fields.html" title="Writing custom model fields">previous</a> 
     |
    <a href="index.html" title="&amp;#8220;How-to&amp;#8221; guides" accesskey="U">up</a>
   |
    <a href="custom-file-storage.html" title="Writing a custom storage system">next</a> &raquo;</div>
    </div>
    
    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="howto-custom-template-tags">
            
  <div class="section" id="s-custom-template-tags-and-filters">
<span id="s-howto-custom-template-tags"></span><span id="custom-template-tags-and-filters"></span><span id="howto-custom-template-tags"></span><h1>Custom template tags and filters<a class="headerlink" href="#custom-template-tags-and-filters" title="Permalink to this headline">¶</a></h1>
<div class="section" id="s-introduction">
<span id="introduction"></span><h2>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
<p>Django&#8217;s template system comes with a wide variety of <a class="reference external" href="../ref/templates/builtins.html#ref-templates-builtins"><em>built-in
tags and filters</em></a> designed to address the
presentation logic needs of your application. Nevertheless, you may
find yourself needing functionality that is not covered by the core
set of template primitives. You can extend the template engine by
defining custom tags and filters using Python, and then make them
available to your templates using the <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">load</span> <span class="pre">%}</span></tt> tag.</p>
<div class="section" id="s-code-layout">
<span id="code-layout"></span><h3>Code layout<a class="headerlink" href="#code-layout" title="Permalink to this headline">¶</a></h3>
<p>Custom template tags and filters must live inside a Django app. If they relate
to an existing app it makes sense to bundle them there; otherwise, you should
create a new app to hold them.</p>
<p>The app should contain a <tt class="docutils literal"><span class="pre">templatetags</span></tt> directory, at the same level as
<tt class="docutils literal"><span class="pre">models.py</span></tt>, <tt class="docutils literal"><span class="pre">views.py</span></tt>, etc. If this doesn&#8217;t already exist, create it -
don&#8217;t forget the <tt class="docutils literal"><span class="pre">__init__.py</span></tt> file to ensure the directory is treated as a
Python package.</p>
<p>Your custom tags and filters will live in a module inside the <tt class="docutils literal"><span class="pre">templatetags</span></tt>
directory. The name of the module file is the name you&#8217;ll use to load the tags
later, so be careful to pick a name that won&#8217;t clash with custom tags and
filters in another app.</p>
<p>For example, if your custom tags/filters are in a file called
<tt class="docutils literal"><span class="pre">poll_extras.py</span></tt>, your app layout might look like this:</p>
<div class="highlight-python"><pre>polls/
    models.py
    templatetags/
        __init__.py
        poll_extras.py
    views.py</pre>
</div>
<p>And in your template you would use the following:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">load</span> <span class="nv">poll_extras</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>The app that contains the custom tags must be in <a class="reference external" href="../ref/settings.html#setting-INSTALLED_APPS"><tt class="xref docutils literal"><span class="pre">INSTALLED_APPS</span></tt></a> in
order for the <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">load</span> <span class="pre">%}</span></tt> tag to work. This is a security feature: It allows
you to host Python code for many template libraries on a single host machine
without enabling access to all of them for every Django installation.</p>
<p>There's no limit on how many modules you put in the <tt class="docutils literal"><span class="pre">templatetags</span></tt> package.
Just keep in mind that a <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">load</span> <span class="pre">%}</span></tt> statement will load tags/filters for
the given Python module name, not the name of the app.</p>
<p>To be a valid tag library, the module must contain a module-level variable
named <tt class="docutils literal"><span class="pre">register</span></tt> that is a <tt class="docutils literal"><span class="pre">template.Library</span></tt> instance, in which all the
tags and filters are registered. So, near the top of your module, put the
following:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">template</span>

<span class="n">register</span> <span class="o">=</span> <span class="n">template</span><span class="o">.</span><span class="n">Library</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition-behind-the-scenes admonition ">
<p class="first admonition-title">Behind the scenes</p>
<p class="last">For a ton of examples, read the source code for Django's default filters
and tags. They're in <tt class="docutils literal"><span class="pre">django/template/defaultfilters.py</span></tt> and
<tt class="docutils literal"><span class="pre">django/template/defaulttags.py</span></tt>, respectively.</p>
</div>
</div>
<div class="section" id="s-writing-custom-template-filters">
<span id="writing-custom-template-filters"></span><h3>Writing custom template filters<a class="headerlink" href="#writing-custom-template-filters" title="Permalink to this headline">¶</a></h3>
<p>Custom filters are just Python functions that take one or two arguments:</p>
<ul class="simple">
<li>The value of the variable (input) -- not necessarily a string.</li>
<li>The value of the argument -- this can have a default value, or be left
out altogether.</li>
</ul>
<p>For example, in the filter <tt class="docutils literal"><span class="pre">{{</span> <span class="pre">var|foo:&quot;bar&quot;</span> <span class="pre">}}</span></tt>, the filter <tt class="docutils literal"><span class="pre">foo</span></tt> would be
passed the variable <tt class="docutils literal"><span class="pre">var</span></tt> and the argument <tt class="docutils literal"><span class="pre">&quot;bar&quot;</span></tt>.</p>
<p>Filter functions should always return something. They shouldn't raise
exceptions. They should fail silently. In case of error, they should return
either the original input or an empty string -- whichever makes more sense.</p>
<p>Here's an example filter definition:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">cut</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">arg</span><span class="p">):</span>
    <span class="s">&quot;Removes all values of arg from the given string&quot;</span>
    <span class="k">return</span> <span class="n">value</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="s">&#39;&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>And here's an example of how that filter would be used:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{{</span> <span class="nv">somevariable</span><span class="o">|</span><span class="nf">cut</span><span class="s2">:&quot;0&quot;</span> <span class="cp">}}</span>
</pre></div>
</div>
<p>Most filters don't take arguments. In this case, just leave the argument out of
your function. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">lower</span><span class="p">(</span><span class="n">value</span><span class="p">):</span> <span class="c"># Only one argument.</span>
    <span class="s">&quot;Converts a string into all lowercase&quot;</span>
    <span class="k">return</span> <span class="n">value</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>
</pre></div>
</div>
<div class="section" id="s-template-filters-that-expect-strings">
<span id="template-filters-that-expect-strings"></span><h4>Template filters that expect strings<a class="headerlink" href="#template-filters-that-expect-strings" title="Permalink to this headline">¶</a></h4>
<p>If you're writing a template filter that only expects a string as the first
argument, you should use the decorator <tt class="docutils literal"><span class="pre">stringfilter</span></tt>. This will
convert an object to its string value before being passed to your function:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.template.defaultfilters</span> <span class="kn">import</span> <span class="n">stringfilter</span>

<span class="nd">@stringfilter</span>
<span class="k">def</span> <span class="nf">lower</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">value</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>
</pre></div>
</div>
<p>This way, you'll be able to pass, say, an integer to this filter, and it
won't cause an <tt class="docutils literal"><span class="pre">AttributeError</span></tt> (because integers don't have <tt class="docutils literal"><span class="pre">lower()</span></tt>
methods).</p>
</div>
<div class="section" id="s-registering-custom-filters">
<span id="registering-custom-filters"></span><h4>Registering custom filters<a class="headerlink" href="#registering-custom-filters" title="Permalink to this headline">¶</a></h4>
<p>Once you've written your filter definition, you need to register it with
your <tt class="docutils literal"><span class="pre">Library</span></tt> instance, to make it available to Django's template language:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">register</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="s">&#39;cut&#39;</span><span class="p">,</span> <span class="n">cut</span><span class="p">)</span>
<span class="n">register</span><span class="o">.</span><span class="n">filter</span><span class="p">(</span><span class="s">&#39;lower&#39;</span><span class="p">,</span> <span class="n">lower</span><span class="p">)</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">Library.filter()</span></tt> method takes two arguments:</p>
<ol class="arabic simple">
<li>The name of the filter -- a string.</li>
<li>The compilation function -- a Python function (not the name of the
function as a string).</li>
</ol>
<p>If you're using Python 2.4 or above, you can use <tt class="docutils literal"><span class="pre">register.filter()</span></tt> as a
decorator instead:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.filter</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&#39;cut&#39;</span><span class="p">)</span>
<span class="nd">@stringfilter</span>
<span class="k">def</span> <span class="nf">cut</span><span class="p">(</span><span class="n">value</span><span class="p">,</span> <span class="n">arg</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">value</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">arg</span><span class="p">,</span> <span class="s">&#39;&#39;</span><span class="p">)</span>

<span class="nd">@register.filter</span>
<span class="nd">@stringfilter</span>
<span class="k">def</span> <span class="nf">lower</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">value</span><span class="o">.</span><span class="n">lower</span><span class="p">()</span>
</pre></div>
</div>
<p>If you leave off the <tt class="docutils literal"><span class="pre">name</span></tt> argument, as in the second example above, Django
will use the function's name as the filter name.</p>
</div>
<div class="section" id="s-filters-and-auto-escaping">
<span id="filters-and-auto-escaping"></span><h4>Filters and auto-escaping<a class="headerlink" href="#filters-and-auto-escaping" title="Permalink to this headline">¶</a></h4>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="../releases/1.0.html#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>When writing a custom filter, give some thought to how the filter will interact
with Django's auto-escaping behavior. Note that three types of strings can be
passed around inside the template code:</p>
<ul>
<li><p class="first"><strong>Raw strings</strong> are the native Python <tt class="docutils literal"><span class="pre">str</span></tt> or <tt class="docutils literal"><span class="pre">unicode</span></tt> types. On
output, they're escaped if auto-escaping is in effect and presented
unchanged, otherwise.</p>
</li>
<li><p class="first"><strong>Safe strings</strong> are strings that have been marked safe from further
escaping at output time. Any necessary escaping has already been done.
They're commonly used for output that contains raw HTML that is intended
to be interpreted as-is on the client side.</p>
<p>Internally, these strings are of type <tt class="docutils literal"><span class="pre">SafeString</span></tt> or <tt class="docutils literal"><span class="pre">SafeUnicode</span></tt>.
They share a common base class of <tt class="docutils literal"><span class="pre">SafeData</span></tt>, so you can test
for them using code like:</p>
<div class="highlight-python"><pre>if isinstance(value, SafeData):
    # Do something with the "safe" string.</pre>
</div>
</li>
<li><p class="first"><strong>Strings marked as &quot;needing escaping&quot;</strong> are <em>always</em> escaped on
output, regardless of whether they are in an <tt class="docutils literal"><span class="pre">autoescape</span></tt> block or not.
These strings are only escaped once, however, even if auto-escaping
applies.</p>
<p>Internally, these strings are of type <tt class="docutils literal"><span class="pre">EscapeString</span></tt> or
<tt class="docutils literal"><span class="pre">EscapeUnicode</span></tt>. Generally you don't have to worry about these; they
exist for the implementation of the <tt class="docutils literal"><span class="pre">escape</span></tt> filter.</p>
</li>
</ul>
<p>Template filter code falls into one of two situations:</p>
<ol class="arabic">
<li><p class="first">Your filter does not introduce any HTML-unsafe characters (<tt class="docutils literal"><span class="pre">&lt;</span></tt>, <tt class="docutils literal"><span class="pre">&gt;</span></tt>,
<tt class="docutils literal"><span class="pre">'</span></tt>, <tt class="docutils literal"><span class="pre">&quot;</span></tt> or <tt class="docutils literal"><span class="pre">&amp;</span></tt>) into the result that were not already present. In
this case, you can let Django take care of all the auto-escaping
handling for you. All you need to do is put the <tt class="docutils literal"><span class="pre">is_safe</span></tt> attribute on
your filter function and set it to <tt class="xref docutils literal"><span class="pre">True</span></tt>, like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.filter</span>
<span class="k">def</span> <span class="nf">myfilter</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">value</span>
<span class="n">myfilter</span><span class="o">.</span><span class="n">is_safe</span> <span class="o">=</span> <span class="bp">True</span>
</pre></div>
</div>
<p>This attribute tells Django that if a &quot;safe&quot; string is passed into your
filter, the result will still be &quot;safe&quot; and if a non-safe string is
passed in, Django will automatically escape it, if necessary.</p>
<p>You can think of this as meaning &quot;this filter is safe -- it doesn't
introduce any possibility of unsafe HTML.&quot;</p>
<p>The reason <tt class="docutils literal"><span class="pre">is_safe</span></tt> is necessary is because there are plenty of
normal string operations that will turn a <tt class="docutils literal"><span class="pre">SafeData</span></tt> object back into
a normal <tt class="docutils literal"><span class="pre">str</span></tt> or <tt class="docutils literal"><span class="pre">unicode</span></tt> object and, rather than try to catch
them all, which would be very difficult, Django repairs the damage after
the filter has completed.</p>
<p>For example, suppose you have a filter that adds the string <tt class="docutils literal"><span class="pre">xx</span></tt> to the
end of any input. Since this introduces no dangerous HTML characters to
the result (aside from any that were already present), you should mark
your filter with <tt class="docutils literal"><span class="pre">is_safe</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.filter</span>
<span class="k">def</span> <span class="nf">add_xx</span><span class="p">(</span><span class="n">value</span><span class="p">):</span>
    <span class="k">return</span> <span class="s">&#39;</span><span class="si">%s</span><span class="s">xx&#39;</span> <span class="o">%</span> <span class="n">value</span>
<span class="n">add_xx</span><span class="o">.</span><span class="n">is_safe</span> <span class="o">=</span> <span class="bp">True</span>
</pre></div>
</div>
<p>When this filter is used in a template where auto-escaping is enabled,
Django will escape the output whenever the input is not already marked as
&quot;safe&quot;.</p>
<p>By default, <tt class="docutils literal"><span class="pre">is_safe</span></tt> defaults to <tt class="xref docutils literal"><span class="pre">False</span></tt>, and you can omit it from
any filters where it isn't required.</p>
<p>Be careful when deciding if your filter really does leave safe strings
as safe. If you're <em>removing</em> characters, you might inadvertently leave
unbalanced HTML tags or entities in the result. For example, removing a
<tt class="docutils literal"><span class="pre">&gt;</span></tt> from the input might turn <tt class="docutils literal"><span class="pre">&lt;a&gt;</span></tt> into <tt class="docutils literal"><span class="pre">&lt;a</span></tt>, which would need to
be escaped on output to avoid causing problems. Similarly, removing a
semicolon (<tt class="docutils literal"><span class="pre">;</span></tt>) can turn <tt class="docutils literal"><span class="pre">&amp;amp;</span></tt> into <tt class="docutils literal"><span class="pre">&amp;amp</span></tt>, which is no longer a
valid entity and thus needs further escaping. Most cases won't be nearly
this tricky, but keep an eye out for any problems like that when
reviewing your code.</p>
<p>Marking a filter <tt class="docutils literal"><span class="pre">is_safe</span></tt> will coerce the filter's return value to
a string.  If your filter should return a boolean or other non-string
value, marking it <tt class="docutils literal"><span class="pre">is_safe</span></tt> will probably have unintended
consequences (such as converting a boolean False to the string
'False').</p>
</li>
<li><p class="first">Alternatively, your filter code can manually take care of any necessary
escaping. This is necessary when you're introducing new HTML markup into
the result. You want to mark the output as safe from further
escaping so that your HTML markup isn't escaped further, so you'll need
to handle the input yourself.</p>
<p>To mark the output as a safe string, use
<tt class="xref docutils literal"><span class="pre">django.utils.safestring.mark_safe()</span></tt>.</p>
<p>Be careful, though. You need to do more than just mark the output as
safe. You need to ensure it really <em>is</em> safe, and what you do depends on
whether auto-escaping is in effect. The idea is to write filters than
can operate in templates where auto-escaping is either on or off in
order to make things easier for your template authors.</p>
<p>In order for your filter to know the current auto-escaping state, set
the <tt class="docutils literal"><span class="pre">needs_autoescape</span></tt> attribute to <tt class="xref docutils literal"><span class="pre">True</span></tt> on your function. (If you
don't specify this attribute, it defaults to <tt class="xref docutils literal"><span class="pre">False</span></tt>). This attribute
tells Django that your filter function wants to be passed an extra
keyword argument, called <tt class="docutils literal"><span class="pre">autoescape</span></tt>, that is <tt class="xref docutils literal"><span class="pre">True</span></tt> if
auto-escaping is in effect and <tt class="xref docutils literal"><span class="pre">False</span></tt> otherwise.</p>
<p>For example, let's write a filter that emphasizes the first character of
a string:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django.utils.html</span> <span class="kn">import</span> <span class="n">conditional_escape</span>
<span class="kn">from</span> <span class="nn">django.utils.safestring</span> <span class="kn">import</span> <span class="n">mark_safe</span>

<span class="k">def</span> <span class="nf">initial_letter_filter</span><span class="p">(</span><span class="n">text</span><span class="p">,</span> <span class="n">autoescape</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
    <span class="n">first</span><span class="p">,</span> <span class="n">other</span> <span class="o">=</span> <span class="n">text</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">text</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span>
    <span class="k">if</span> <span class="n">autoescape</span><span class="p">:</span>
        <span class="n">esc</span> <span class="o">=</span> <span class="n">conditional_escape</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">esc</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="n">x</span>
    <span class="n">result</span> <span class="o">=</span> <span class="s">&#39;&lt;strong&gt;</span><span class="si">%s</span><span class="s">&lt;/strong&gt;</span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">esc</span><span class="p">(</span><span class="n">first</span><span class="p">),</span> <span class="n">esc</span><span class="p">(</span><span class="n">other</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">mark_safe</span><span class="p">(</span><span class="n">result</span><span class="p">)</span>
<span class="n">initial_letter_filter</span><span class="o">.</span><span class="n">needs_autoescape</span> <span class="o">=</span> <span class="bp">True</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">needs_autoescape</span></tt> attribute on the filter function and the
<tt class="docutils literal"><span class="pre">autoescape</span></tt> keyword argument mean that our function will know whether
automatic escaping is in effect when the filter is called. We use
<tt class="docutils literal"><span class="pre">autoescape</span></tt> to decide whether the input data needs to be passed
through <tt class="docutils literal"><span class="pre">django.utils.html.conditional_escape</span></tt> or not. (In the latter
case, we just use the identity function as the &quot;escape&quot; function.) The
<tt class="docutils literal"><span class="pre">conditional_escape()</span></tt> function is like <tt class="docutils literal"><span class="pre">escape()</span></tt> except it only
escapes input that is <strong>not</strong> a <tt class="docutils literal"><span class="pre">SafeData</span></tt> instance. If a <tt class="docutils literal"><span class="pre">SafeData</span></tt>
instance is passed to <tt class="docutils literal"><span class="pre">conditional_escape()</span></tt>, the data is returned
unchanged.</p>
<p>Finally, in the above example, we remember to mark the result as safe
so that our HTML is inserted directly into the template without further
escaping.</p>
<p>There's no need to worry about the <tt class="docutils literal"><span class="pre">is_safe</span></tt> attribute in this case
(although including it wouldn't hurt anything). Whenever you manually
handle the auto-escaping issues and return a safe string, the
<tt class="docutils literal"><span class="pre">is_safe</span></tt> attribute won't change anything either way.</p>
</li>
</ol>
</div>
</div>
<div class="section" id="s-writing-custom-template-tags">
<span id="writing-custom-template-tags"></span><h3>Writing custom template tags<a class="headerlink" href="#writing-custom-template-tags" title="Permalink to this headline">¶</a></h3>
<p>Tags are more complex than filters, because tags can do anything.</p>
<div class="section" id="s-a-quick-overview">
<span id="a-quick-overview"></span><h4>A quick overview<a class="headerlink" href="#a-quick-overview" title="Permalink to this headline">¶</a></h4>
<p>Above, this document explained that the template system works in a two-step
process: compiling and rendering. To define a custom template tag, you specify
how the compilation works and how the rendering works.</p>
<p>When Django compiles a template, it splits the raw template text into
''nodes''. Each node is an instance of <tt class="docutils literal"><span class="pre">django.template.Node</span></tt> and has
a <tt class="docutils literal"><span class="pre">render()</span></tt> method. A compiled template is, simply, a list of <tt class="docutils literal"><span class="pre">Node</span></tt>
objects. When you call <tt class="docutils literal"><span class="pre">render()</span></tt> on a compiled template object, the template
calls <tt class="docutils literal"><span class="pre">render()</span></tt> on each <tt class="docutils literal"><span class="pre">Node</span></tt> in its node list, with the given context.
The results are all concatenated together to form the output of the template.</p>
<p>Thus, to define a custom template tag, you specify how the raw template tag is
converted into a <tt class="docutils literal"><span class="pre">Node</span></tt> (the compilation function), and what the node's
<tt class="docutils literal"><span class="pre">render()</span></tt> method does.</p>
</div>
<div class="section" id="s-writing-the-compilation-function">
<span id="writing-the-compilation-function"></span><h4>Writing the compilation function<a class="headerlink" href="#writing-the-compilation-function" title="Permalink to this headline">¶</a></h4>
<p>For each template tag the template parser encounters, it calls a Python
function with the tag contents and the parser object itself. This function is
responsible for returning a <tt class="docutils literal"><span class="pre">Node</span></tt> instance based on the contents of the tag.</p>
<p>For example, let's write a template tag, <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">current_time</span> <span class="pre">%}</span></tt>, that displays
the current date/time, formatted according to a parameter given in the tag, in
<a class="reference external" href="http://docs.python.org/library/time.html#time.strftime">strftime syntax</a>. It's a good idea to decide the tag syntax before anything
else. In our case, let's say the tag should be used like this:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="nt">&lt;p&gt;</span>The time is <span class="cp">{%</span> <span class="k">current_time</span> <span class="s2">&quot;%Y-%m-%d %I:%M %p&quot;</span> <span class="cp">%}</span>.<span class="nt">&lt;/p&gt;</span>
</pre></div>
</div>
<p>The parser for this function should grab the parameter and create a <tt class="docutils literal"><span class="pre">Node</span></tt>
object:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">template</span>
<span class="k">def</span> <span class="nf">do_current_time</span><span class="p">(</span><span class="n">parser</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="c"># split_contents() knows not to split quoted strings.</span>
        <span class="n">tag_name</span><span class="p">,</span> <span class="n">format_string</span> <span class="o">=</span> <span class="n">token</span><span class="o">.</span><span class="n">split_contents</span><span class="p">()</span>
    <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">template</span><span class="o">.</span><span class="n">TemplateSyntaxError</span><span class="p">,</span> <span class="s">&quot;</span><span class="si">%r</span><span class="s"> tag requires a single argument&quot;</span> <span class="o">%</span> <span class="n">token</span><span class="o">.</span><span class="n">contents</span><span class="o">.</span><span class="n">split</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span><span class="n">format_string</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">==</span> <span class="n">format_string</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="ow">and</span> <span class="n">format_string</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&#39;&quot;&#39;</span><span class="p">,</span> <span class="s">&quot;&#39;&quot;</span><span class="p">)):</span>
        <span class="k">raise</span> <span class="n">template</span><span class="o">.</span><span class="n">TemplateSyntaxError</span><span class="p">,</span> <span class="s">&quot;</span><span class="si">%r</span><span class="s"> tag&#39;s argument should be in quotes&quot;</span> <span class="o">%</span> <span class="n">tag_name</span>
    <span class="k">return</span> <span class="n">CurrentTimeNode</span><span class="p">(</span><span class="n">format_string</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span>
</pre></div>
</div>
<p>Notes:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">parser</span></tt> is the template parser object. We don't need it in this
example.</li>
<li><tt class="docutils literal"><span class="pre">token.contents</span></tt> is a string of the raw contents of the tag. In our
example, it's <tt class="docutils literal"><span class="pre">'current_time</span> <span class="pre">&quot;%Y-%m-%d</span> <span class="pre">%I:%M</span> <span class="pre">%p&quot;'</span></tt>.</li>
<li>The <tt class="docutils literal"><span class="pre">token.split_contents()</span></tt> method separates the arguments on spaces
while keeping quoted strings together. The more straightforward
<tt class="docutils literal"><span class="pre">token.contents.split()</span></tt> wouldn't be as robust, as it would naively
split on <em>all</em> spaces, including those within quoted strings. It's a good
idea to always use <tt class="docutils literal"><span class="pre">token.split_contents()</span></tt>.</li>
<li>This function is responsible for raising
<tt class="docutils literal"><span class="pre">django.template.TemplateSyntaxError</span></tt>, with helpful messages, for
any syntax error.</li>
<li>The <tt class="docutils literal"><span class="pre">TemplateSyntaxError</span></tt> exceptions use the <tt class="docutils literal"><span class="pre">tag_name</span></tt> variable.
Don't hard-code the tag's name in your error messages, because that
couples the tag's name to your function. <tt class="docutils literal"><span class="pre">token.contents.split()[0]</span></tt>
will ''always'' be the name of your tag -- even when the tag has no
arguments.</li>
<li>The function returns a <tt class="docutils literal"><span class="pre">CurrentTimeNode</span></tt> with everything the node needs
to know about this tag. In this case, it just passes the argument --
<tt class="docutils literal"><span class="pre">&quot;%Y-%m-%d</span> <span class="pre">%I:%M</span> <span class="pre">%p&quot;</span></tt>. The leading and trailing quotes from the
template tag are removed in <tt class="docutils literal"><span class="pre">format_string[1:-1]</span></tt>.</li>
<li>The parsing is very low-level. The Django developers have experimented
with writing small frameworks on top of this parsing system, using
techniques such as EBNF grammars, but those experiments made the template
engine too slow. It's low-level because that's fastest.</li>
</ul>
</div>
<div class="section" id="s-writing-the-renderer">
<span id="writing-the-renderer"></span><h4>Writing the renderer<a class="headerlink" href="#writing-the-renderer" title="Permalink to this headline">¶</a></h4>
<p>The second step in writing custom tags is to define a <tt class="docutils literal"><span class="pre">Node</span></tt> subclass that
has a <tt class="docutils literal"><span class="pre">render()</span></tt> method.</p>
<p>Continuing the above example, we need to define <tt class="docutils literal"><span class="pre">CurrentTimeNode</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">template</span>
<span class="kn">import</span> <span class="nn">datetime</span>
<span class="k">class</span> <span class="nc">CurrentTimeNode</span><span class="p">(</span><span class="n">template</span><span class="o">.</span><span class="n">Node</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">format_string</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">format_string</span> <span class="o">=</span> <span class="n">format_string</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="p">):</span>
        <span class="k">return</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">format_string</span><span class="p">)</span>
</pre></div>
</div>
<p>Notes:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">__init__()</span></tt> gets the <tt class="docutils literal"><span class="pre">format_string</span></tt> from <tt class="docutils literal"><span class="pre">do_current_time()</span></tt>.
Always pass any options/parameters/arguments to a <tt class="docutils literal"><span class="pre">Node</span></tt> via its
<tt class="docutils literal"><span class="pre">__init__()</span></tt>.</li>
<li>The <tt class="docutils literal"><span class="pre">render()</span></tt> method is where the work actually happens.</li>
<li><tt class="docutils literal"><span class="pre">render()</span></tt> should never raise <tt class="docutils literal"><span class="pre">TemplateSyntaxError</span></tt> or any other
exception. It should fail silently, just as template filters should.</li>
</ul>
<p>Ultimately, this decoupling of compilation and rendering results in an
efficient template system, because a template can render multiple contexts
without having to be parsed multiple times.</p>
</div>
<div class="section" id="s-auto-escaping-considerations">
<span id="auto-escaping-considerations"></span><h4>Auto-escaping considerations<a class="headerlink" href="#auto-escaping-considerations" title="Permalink to this headline">¶</a></h4>
<div class="versionadded">
<span class="title">New in Django 1.0:</span> <a class="reference external" href="../releases/1.0.html#releases-1-0"><em>Please, see the release notes</em></a></div>
<p>The output from template tags is <strong>not</strong> automatically run through the
auto-escaping filters. However, there are still a couple of things you should
keep in mind when writing a template tag.</p>
<p>If the <tt class="docutils literal"><span class="pre">render()</span></tt> function of your template stores the result in a context
variable (rather than returning the result in a string), it should take care
to call <tt class="docutils literal"><span class="pre">mark_safe()</span></tt> if appropriate. When the variable is ultimately
rendered, it will be affected by the auto-escape setting in effect at the
time, so content that should be safe from further escaping needs to be marked
as such.</p>
<p>Also, if your template tag creates a new context for performing some
sub-rendering, set the auto-escape attribute to the current context's value.
The <tt class="docutils literal"><span class="pre">__init__</span></tt> method for the <tt class="docutils literal"><span class="pre">Context</span></tt> class takes a parameter called
<tt class="docutils literal"><span class="pre">autoescape</span></tt> that you can use for this purpose. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><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="p">):</span>
    <span class="c"># ...</span>
    <span class="n">new_context</span> <span class="o">=</span> <span class="n">Context</span><span class="p">({</span><span class="s">&#39;var&#39;</span><span class="p">:</span> <span class="n">obj</span><span class="p">},</span> <span class="n">autoescape</span><span class="o">=</span><span class="n">context</span><span class="o">.</span><span class="n">autoescape</span><span class="p">)</span>
    <span class="c"># ... Do something with new_context ...</span>
</pre></div>
</div>
<p>This is not a very common situation, but it's useful if you're rendering a
template yourself. For example:</p>
<div class="highlight-python"><div class="highlight"><pre><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="p">):</span>
    <span class="n">t</span> <span class="o">=</span> <span class="n">template</span><span class="o">.</span><span class="n">loader</span><span class="o">.</span><span class="n">get_template</span><span class="p">(</span><span class="s">&#39;small_fragment.html&#39;</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">t</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">Context</span><span class="p">({</span><span class="s">&#39;var&#39;</span><span class="p">:</span> <span class="n">obj</span><span class="p">},</span> <span class="n">autoescape</span><span class="o">=</span><span class="n">context</span><span class="o">.</span><span class="n">autoescape</span><span class="p">))</span>
</pre></div>
</div>
<p>If we had neglected to pass in the current <tt class="docutils literal"><span class="pre">context.autoescape</span></tt> value to our
new <tt class="docutils literal"><span class="pre">Context</span></tt> in this example, the results would have <em>always</em> been
automatically escaped, which may not be the desired behavior if the template
tag is used inside a <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">autoescape</span> <span class="pre">off</span> <span class="pre">%}</span></tt> block.</p>
</div>
<div class="section" id="s-registering-the-tag">
<span id="registering-the-tag"></span><h4>Registering the tag<a class="headerlink" href="#registering-the-tag" title="Permalink to this headline">¶</a></h4>
<p>Finally, register the tag with your module's <tt class="docutils literal"><span class="pre">Library</span></tt> instance, as explained
in &quot;Writing custom template filters&quot; above. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">register</span><span class="o">.</span><span class="n">tag</span><span class="p">(</span><span class="s">&#39;current_time&#39;</span><span class="p">,</span> <span class="n">do_current_time</span><span class="p">)</span>
</pre></div>
</div>
<p>The <tt class="docutils literal"><span class="pre">tag()</span></tt> method takes two arguments:</p>
<ol class="arabic simple">
<li>The name of the template tag -- a string. If this is left out, the
name of the compilation function will be used.</li>
<li>The compilation function -- a Python function (not the name of the
function as a string).</li>
</ol>
<p>As with filter registration, it is also possible to use this as a decorator, in
Python 2.4 and above:</p>
<div class="highlight-python"><pre>@register.tag(name="current_time")
def do_current_time(parser, token):
    # ...

@register.tag
def shout(parser, token):
    # ...</pre>
</div>
<p>If you leave off the <tt class="docutils literal"><span class="pre">name</span></tt> argument, as in the second example above, Django
will use the function's name as the tag name.</p>
</div>
<div class="section" id="s-passing-template-variables-to-the-tag">
<span id="passing-template-variables-to-the-tag"></span><h4>Passing template variables to the tag<a class="headerlink" href="#passing-template-variables-to-the-tag" title="Permalink to this headline">¶</a></h4>
<p>Although you can pass any number of arguments to a template tag using
<tt class="docutils literal"><span class="pre">token.split_contents()</span></tt>, the arguments are all unpacked as
string literals. A little more work is required in order to pass dynamic
content (a template variable) to a template tag as an argument.</p>
<p>While the previous examples have formatted the current time into a string and
returned the string, suppose you wanted to pass in a <tt class="docutils literal"><span class="pre">DateTimeField</span></tt> from an
object and have the template tag format that date-time:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="nt">&lt;p&gt;</span>This post was last updated at <span class="cp">{%</span> <span class="k">format_time</span> <span class="nv">blog_entry.date_updated</span> <span class="s2">&quot;%Y-%m-%d %I:%M %p&quot;</span> <span class="cp">%}</span>.<span class="nt">&lt;/p&gt;</span>
</pre></div>
</div>
<p>Initially, <tt class="docutils literal"><span class="pre">token.split_contents()</span></tt> will return three values:</p>
<ol class="arabic simple">
<li>The tag name <tt class="docutils literal"><span class="pre">format_time</span></tt>.</li>
<li>The string &quot;blog_entry.date_updated&quot; (without the surrounding quotes).</li>
<li>The formatting string &quot;%Y-%m-%d %I:%M %p&quot;. The return value from
<tt class="docutils literal"><span class="pre">split_contents()</span></tt> will include the leading and trailing quotes for
string literals like this.</li>
</ol>
<p>Now your tag should begin to look like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">from</span> <span class="nn">django</span> <span class="kn">import</span> <span class="n">template</span>
<span class="k">def</span> <span class="nf">do_format_time</span><span class="p">(</span><span class="n">parser</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="c"># split_contents() knows not to split quoted strings.</span>
        <span class="n">tag_name</span><span class="p">,</span> <span class="n">date_to_be_formatted</span><span class="p">,</span> <span class="n">format_string</span> <span class="o">=</span> <span class="n">token</span><span class="o">.</span><span class="n">split_contents</span><span class="p">()</span>
    <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">template</span><span class="o">.</span><span class="n">TemplateSyntaxError</span><span class="p">,</span> <span class="s">&quot;</span><span class="si">%r</span><span class="s"> tag requires exactly two arguments&quot;</span> <span class="o">%</span> <span class="n">token</span><span class="o">.</span><span class="n">contents</span><span class="o">.</span><span class="n">split</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span><span class="n">format_string</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">==</span> <span class="n">format_string</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="ow">and</span> <span class="n">format_string</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&#39;&quot;&#39;</span><span class="p">,</span> <span class="s">&quot;&#39;&quot;</span><span class="p">)):</span>
        <span class="k">raise</span> <span class="n">template</span><span class="o">.</span><span class="n">TemplateSyntaxError</span><span class="p">,</span> <span class="s">&quot;</span><span class="si">%r</span><span class="s"> tag&#39;s argument should be in quotes&quot;</span> <span class="o">%</span> <span class="n">tag_name</span>
    <span class="k">return</span> <span class="n">FormatTimeNode</span><span class="p">(</span><span class="n">date_to_be_formatted</span><span class="p">,</span> <span class="n">format_string</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span>
</pre></div>
</div>
<div class="versionchanged">
<span class="title">Changed in Django 1.0:</span> Variable resolution has changed in the 1.0 release of Django. <tt class="docutils literal"><span class="pre">template.resolve_variable()</span></tt>
has been deprecated in favor of a new <tt class="docutils literal"><span class="pre">template.Variable</span></tt> class.</div>
<p>You also have to change the renderer to retrieve the actual contents of the
<tt class="docutils literal"><span class="pre">date_updated</span></tt> property of the <tt class="docutils literal"><span class="pre">blog_entry</span></tt> object.  This can be
accomplished by using the <tt class="docutils literal"><span class="pre">Variable()</span></tt> class in <tt class="docutils literal"><span class="pre">django.template</span></tt>.</p>
<p>To use the <tt class="docutils literal"><span class="pre">Variable</span></tt> class, simply instantiate it with the name of the
variable to be resolved, and then call <tt class="docutils literal"><span class="pre">variable.resolve(context)</span></tt>. So,
for example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">FormatTimeNode</span><span class="p">(</span><span class="n">template</span><span class="o">.</span><span class="n">Node</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">date_to_be_formatted</span><span class="p">,</span> <span class="n">format_string</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">date_to_be_formatted</span> <span class="o">=</span> <span class="n">template</span><span class="o">.</span><span class="n">Variable</span><span class="p">(</span><span class="n">date_to_be_formatted</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">format_string</span> <span class="o">=</span> <span class="n">format_string</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="p">):</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">actual_date</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">date_to_be_formatted</span><span class="o">.</span><span class="n">resolve</span><span class="p">(</span><span class="n">context</span><span class="p">)</span>
            <span class="k">return</span> <span class="n">actual_date</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">format_string</span><span class="p">)</span>
        <span class="k">except</span> <span class="n">template</span><span class="o">.</span><span class="n">VariableDoesNotExist</span><span class="p">:</span>
            <span class="k">return</span> <span class="s">&#39;&#39;</span>
</pre></div>
</div>
<p>Variable resolution will throw a <tt class="docutils literal"><span class="pre">VariableDoesNotExist</span></tt> exception if it cannot
resolve the string passed to it in the current context of the page.</p>
</div>
<div class="section" id="s-shortcut-for-simple-tags">
<span id="shortcut-for-simple-tags"></span><h4>Shortcut for simple tags<a class="headerlink" href="#shortcut-for-simple-tags" title="Permalink to this headline">¶</a></h4>
<p>Many template tags take a number of arguments -- strings or a template variables
-- and return a string after doing some processing based solely on
the input argument and some external information. For example, the
<tt class="docutils literal"><span class="pre">current_time</span></tt> tag we wrote above is of this variety: we give it a format
string, it returns the time as a string.</p>
<p>To ease the creation of the types of tags, Django provides a helper function,
<tt class="docutils literal"><span class="pre">simple_tag</span></tt>. This function, which is a method of
<tt class="docutils literal"><span class="pre">django.template.Library</span></tt>, takes a function that accepts any number of
arguments, wraps it in a <tt class="docutils literal"><span class="pre">render</span></tt> function and the other necessary bits
mentioned above and registers it with the template system.</p>
<p>Our earlier <tt class="docutils literal"><span class="pre">current_time</span></tt> function could thus be written like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">current_time</span><span class="p">(</span><span class="n">format_string</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="n">format_string</span><span class="p">)</span>

<span class="n">register</span><span class="o">.</span><span class="n">simple_tag</span><span class="p">(</span><span class="n">current_time</span><span class="p">)</span>
</pre></div>
</div>
<p>In Python 2.4, the decorator syntax also works:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.simple_tag</span>
<span class="k">def</span> <span class="nf">current_time</span><span class="p">(</span><span class="n">format_string</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>A couple of things to note about the <tt class="docutils literal"><span class="pre">simple_tag</span></tt> helper function:</p>
<ul class="simple">
<li>Checking for the required number of arguments, etc., has already been
done by the time our function is called, so we don't need to do that.</li>
<li>The quotes around the argument (if any) have already been stripped away,
so we just receive a plain string.</li>
<li>If the argument was a template variable, our function is passed the
current value of the variable, not the variable itself.</li>
</ul>
<p>When your template tag does not need access to the current context, writing a
function to work with the input values and using the <tt class="docutils literal"><span class="pre">simple_tag</span></tt> helper is
the easiest way to create a new tag.</p>
</div>
<div class="section" id="s-inclusion-tags">
<span id="s-howto-custom-template-tags-inclusion-tags"></span><span id="inclusion-tags"></span><span id="howto-custom-template-tags-inclusion-tags"></span><h4>Inclusion tags<a class="headerlink" href="#inclusion-tags" title="Permalink to this headline">¶</a></h4>
<p>Another common type of template tag is the type that displays some data by
rendering <em>another</em> template. For example, Django's admin interface uses custom
template tags to display the buttons along the bottom of the &quot;add/change&quot; form
pages. Those buttons always look the same, but the link targets change depending
on the object being edited -- so they're a perfect case for using a small
template that is filled with details from the current object. (In the admin's
case, this is the <tt class="docutils literal"><span class="pre">submit_row</span></tt> tag.)</p>
<p>These sorts of tags are called &quot;inclusion tags&quot;.</p>
<p>Writing inclusion tags is probably best demonstrated by example. Let's write a
tag that outputs a list of choices for a given <tt class="docutils literal"><span class="pre">Poll</span></tt> object, such as was
created in the <a class="reference external" href="../intro/tutorial01.html#creating-models"><em>tutorials</em></a>. We'll use the tag like this:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">show_results</span> <span class="nv">poll</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>...and the output will be something like this:</p>
<div class="highlight-html"><div class="highlight"><pre><span class="nt">&lt;ul&gt;</span>
  <span class="nt">&lt;li&gt;</span>First choice<span class="nt">&lt;/li&gt;</span>
  <span class="nt">&lt;li&gt;</span>Second choice<span class="nt">&lt;/li&gt;</span>
  <span class="nt">&lt;li&gt;</span>Third choice<span class="nt">&lt;/li&gt;</span>
<span class="nt">&lt;/ul&gt;</span>
</pre></div>
</div>
<p>First, define the function that takes the argument and produces a dictionary of
data for the result. The important point here is we only need to return a
dictionary, not anything more complex. This will be used as a template context
for the template fragment. Example:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">show_results</span><span class="p">(</span><span class="n">poll</span><span class="p">):</span>
    <span class="n">choices</span> <span class="o">=</span> <span class="n">poll</span><span class="o">.</span><span class="n">choice_set</span><span class="o">.</span><span class="n">all</span><span class="p">()</span>
    <span class="k">return</span> <span class="p">{</span><span class="s">&#39;choices&#39;</span><span class="p">:</span> <span class="n">choices</span><span class="p">}</span>
</pre></div>
</div>
<p>Next, create the template used to render the tag's output. This template is a
fixed feature of the tag: the tag writer specifies it, not the template
designer. Following our example, the template is very simple:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="nt">&lt;ul&gt;</span>
<span class="cp">{%</span> <span class="k">for</span> <span class="nv">choice</span> <span class="k">in</span> <span class="nv">choices</span> <span class="cp">%}</span>
    <span class="nt">&lt;li&gt;</span> <span class="cp">{{</span> <span class="nv">choice</span> <span class="cp">}}</span> <span class="nt">&lt;/li&gt;</span>
<span class="cp">{%</span> <span class="k">endfor</span> <span class="cp">%}</span>
<span class="nt">&lt;/ul&gt;</span>
</pre></div>
</div>
<p>Now, create and register the inclusion tag by calling the <tt class="docutils literal"><span class="pre">inclusion_tag()</span></tt>
method on a <tt class="docutils literal"><span class="pre">Library</span></tt> object. Following our example, if the above template is
in a file called <tt class="docutils literal"><span class="pre">results.html</span></tt> in a directory that's searched by the template
loader, we'd register the tag like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># Here, register is a django.template.Library instance, as before</span>
<span class="n">register</span><span class="o">.</span><span class="n">inclusion_tag</span><span class="p">(</span><span class="s">&#39;results.html&#39;</span><span class="p">)(</span><span class="n">show_results</span><span class="p">)</span>
</pre></div>
</div>
<p>As always, Python 2.4 decorator syntax works as well, so we could have
written:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="nd">@register.inclusion_tag</span><span class="p">(</span><span class="s">&#39;results.html&#39;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">show_results</span><span class="p">(</span><span class="n">poll</span><span class="p">):</span>
    <span class="o">...</span>
</pre></div>
</div>
<p>...when first creating the function.</p>
<p>Sometimes, your inclusion tags might require a large number of arguments,
making it a pain for template authors to pass in all the arguments and remember
their order. To solve this, Django provides a <tt class="docutils literal"><span class="pre">takes_context</span></tt> option for
inclusion tags. If you specify <tt class="docutils literal"><span class="pre">takes_context</span></tt> in creating a template tag,
the tag will have no required arguments, and the underlying Python function
will have one argument -- the template context as of when the tag was called.</p>
<p>For example, say you're writing an inclusion tag that will always be used in a
context that contains <tt class="docutils literal"><span class="pre">home_link</span></tt> and <tt class="docutils literal"><span class="pre">home_title</span></tt> variables that point
back to the main page. Here's what the Python function would look like:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># The first argument *must* be called &quot;context&quot; here.</span>
<span class="k">def</span> <span class="nf">jump_link</span><span class="p">(</span><span class="n">context</span><span class="p">):</span>
    <span class="k">return</span> <span class="p">{</span>
        <span class="s">&#39;link&#39;</span><span class="p">:</span> <span class="n">context</span><span class="p">[</span><span class="s">&#39;home_link&#39;</span><span class="p">],</span>
        <span class="s">&#39;title&#39;</span><span class="p">:</span> <span class="n">context</span><span class="p">[</span><span class="s">&#39;home_title&#39;</span><span class="p">],</span>
    <span class="p">}</span>
<span class="c"># Register the custom tag as an inclusion tag with takes_context=True.</span>
<span class="n">register</span><span class="o">.</span><span class="n">inclusion_tag</span><span class="p">(</span><span class="s">&#39;link.html&#39;</span><span class="p">,</span> <span class="n">takes_context</span><span class="o">=</span><span class="bp">True</span><span class="p">)(</span><span class="n">jump_link</span><span class="p">)</span>
</pre></div>
</div>
<p>(Note that the first parameter to the function <em>must</em> be called <tt class="docutils literal"><span class="pre">context</span></tt>.)</p>
<p>In that <tt class="docutils literal"><span class="pre">register.inclusion_tag()</span></tt> line, we specified <tt class="docutils literal"><span class="pre">takes_context=True</span></tt>
and the name of the template. Here's what the template <tt class="docutils literal"><span class="pre">link.html</span></tt> might look
like:</p>
<div class="highlight-html+django"><div class="highlight"><pre>Jump directly to <span class="nt">&lt;a</span> <span class="na">href=</span><span class="s">&quot;</span><span class="cp">{{</span> <span class="nv">link</span> <span class="cp">}}</span><span class="s">&quot;</span><span class="nt">&gt;</span><span class="cp">{{</span> <span class="nv">title</span> <span class="cp">}}</span><span class="nt">&lt;/a&gt;</span>.
</pre></div>
</div>
<p>Then, any time you want to use that custom tag, load its library and call it
without any arguments, like so:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">jump_link</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>Note that when you're using <tt class="docutils literal"><span class="pre">takes_context=True</span></tt>, there's no need to pass
arguments to the template tag. It automatically gets access to the context.</p>
<p>The <tt class="docutils literal"><span class="pre">takes_context</span></tt> parameter defaults to <tt class="xref docutils literal"><span class="pre">False</span></tt>. When it's set to <em>True</em>,
the tag is passed the context object, as in this example. That's the only
difference between this case and the previous <tt class="docutils literal"><span class="pre">inclusion_tag</span></tt> example.</p>
</div>
<div class="section" id="s-setting-a-variable-in-the-context">
<span id="setting-a-variable-in-the-context"></span><h4>Setting a variable in the context<a class="headerlink" href="#setting-a-variable-in-the-context" title="Permalink to this headline">¶</a></h4>
<p>The above example simply output a value. Generally, it's more flexible if your
template tags set template variables instead of outputting values. That way,
template authors can reuse the values that your template tags create.</p>
<p>To set a variable in the context, just use dictionary assignment on the context
object in the <tt class="docutils literal"><span class="pre">render()</span></tt> method. Here's an updated version of
<tt class="docutils literal"><span class="pre">CurrentTimeNode</span></tt> that sets a template variable <tt class="docutils literal"><span class="pre">current_time</span></tt> instead of
outputting it:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">CurrentTimeNode2</span><span class="p">(</span><span class="n">template</span><span class="o">.</span><span class="n">Node</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">format_string</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">format_string</span> <span class="o">=</span> <span class="n">format_string</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="p">):</span>
        <span class="n">context</span><span class="p">[</span><span class="s">&#39;current_time&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">format_string</span><span class="p">)</span>
        <span class="k">return</span> <span class="s">&#39;&#39;</span>
</pre></div>
</div>
<p>Note that <tt class="docutils literal"><span class="pre">render()</span></tt> returns the empty string. <tt class="docutils literal"><span class="pre">render()</span></tt> should always
return string output. If all the template tag does is set a variable,
<tt class="docutils literal"><span class="pre">render()</span></tt> should return the empty string.</p>
<p>Here's how you'd use this new version of the tag:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">current_time</span> <span class="s2">&quot;%Y-%M-%d %I:%M %p&quot;</span> <span class="cp">%}</span><span class="nt">&lt;p&gt;</span>The time is <span class="cp">{{</span> <span class="nv">current_time</span> <span class="cp">}}</span>.<span class="nt">&lt;/p&gt;</span>
</pre></div>
</div>
<p>But, there's a problem with <tt class="docutils literal"><span class="pre">CurrentTimeNode2</span></tt>: The variable name
<tt class="docutils literal"><span class="pre">current_time</span></tt> is hard-coded. This means you'll need to make sure your
template doesn't use <tt class="docutils literal"><span class="pre">{{</span> <span class="pre">current_time</span> <span class="pre">}}</span></tt> anywhere else, because the
<tt class="docutils literal"><span class="pre">{%</span> <span class="pre">current_time</span> <span class="pre">%}</span></tt> will blindly overwrite that variable's value. A cleaner
solution is to make the template tag specify the name of the output variable,
like so:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">current_time</span> <span class="s2">&quot;%Y-%M-%d %I:%M %p&quot;</span> <span class="k">as</span> <span class="nv">my_current_time</span> <span class="cp">%}</span>
<span class="nt">&lt;p&gt;</span>The current time is <span class="cp">{{</span> <span class="nv">my_current_time</span> <span class="cp">}}</span>.<span class="nt">&lt;/p&gt;</span>
</pre></div>
</div>
<p>To do that, you'll need to refactor both the compilation function and <tt class="docutils literal"><span class="pre">Node</span></tt>
class, like so:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">class</span> <span class="nc">CurrentTimeNode3</span><span class="p">(</span><span class="n">template</span><span class="o">.</span><span class="n">Node</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">format_string</span><span class="p">,</span> <span class="n">var_name</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">format_string</span> <span class="o">=</span> <span class="n">format_string</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">var_name</span> <span class="o">=</span> <span class="n">var_name</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="p">):</span>
        <span class="n">context</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">var_name</span><span class="p">]</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">format_string</span><span class="p">)</span>
        <span class="k">return</span> <span class="s">&#39;&#39;</span>

<span class="kn">import</span> <span class="nn">re</span>
<span class="k">def</span> <span class="nf">do_current_time</span><span class="p">(</span><span class="n">parser</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
    <span class="c"># This version uses a regular expression to parse tag contents.</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="c"># Splitting by None == splitting by spaces.</span>
        <span class="n">tag_name</span><span class="p">,</span> <span class="n">arg</span> <span class="o">=</span> <span class="n">token</span><span class="o">.</span><span class="n">contents</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="bp">None</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
    <span class="k">except</span> <span class="ne">ValueError</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">template</span><span class="o">.</span><span class="n">TemplateSyntaxError</span><span class="p">,</span> <span class="s">&quot;</span><span class="si">%r</span><span class="s"> tag requires arguments&quot;</span> <span class="o">%</span> <span class="n">token</span><span class="o">.</span><span class="n">contents</span><span class="o">.</span><span class="n">split</span><span class="p">()[</span><span class="mi">0</span><span class="p">]</span>
    <span class="n">m</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="s">r&#39;(.*?) as (\w+)&#39;</span><span class="p">,</span> <span class="n">arg</span><span class="p">)</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">m</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">template</span><span class="o">.</span><span class="n">TemplateSyntaxError</span><span class="p">,</span> <span class="s">&quot;</span><span class="si">%r</span><span class="s"> tag had invalid arguments&quot;</span> <span class="o">%</span> <span class="n">tag_name</span>
    <span class="n">format_string</span><span class="p">,</span> <span class="n">var_name</span> <span class="o">=</span> <span class="n">m</span><span class="o">.</span><span class="n">groups</span><span class="p">()</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="p">(</span><span class="n">format_string</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">==</span> <span class="n">format_string</span><span class="p">[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="ow">and</span> <span class="n">format_string</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&#39;&quot;&#39;</span><span class="p">,</span> <span class="s">&quot;&#39;&quot;</span><span class="p">)):</span>
        <span class="k">raise</span> <span class="n">template</span><span class="o">.</span><span class="n">TemplateSyntaxError</span><span class="p">,</span> <span class="s">&quot;</span><span class="si">%r</span><span class="s"> tag&#39;s argument should be in quotes&quot;</span> <span class="o">%</span> <span class="n">tag_name</span>
    <span class="k">return</span> <span class="n">CurrentTimeNode3</span><span class="p">(</span><span class="n">format_string</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="o">-</span><span class="mi">1</span><span class="p">],</span> <span class="n">var_name</span><span class="p">)</span>
</pre></div>
</div>
<p>The difference here is that <tt class="docutils literal"><span class="pre">do_current_time()</span></tt> grabs the format string and
the variable name, passing both to <tt class="docutils literal"><span class="pre">CurrentTimeNode3</span></tt>.</p>
</div>
<div class="section" id="s-parsing-until-another-block-tag">
<span id="parsing-until-another-block-tag"></span><h4>Parsing until another block tag<a class="headerlink" href="#parsing-until-another-block-tag" title="Permalink to this headline">¶</a></h4>
<p>Template tags can work in tandem. For instance, the standard <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">comment</span> <span class="pre">%}</span></tt>
tag hides everything until <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">endcomment</span> <span class="pre">%}</span></tt>. To create a template tag such
as this, use <tt class="docutils literal"><span class="pre">parser.parse()</span></tt> in your compilation function.</p>
<p>Here's how the standard <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">comment</span> <span class="pre">%}</span></tt> tag is implemented:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">do_comment</span><span class="p">(</span><span class="n">parser</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
    <span class="n">nodelist</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse</span><span class="p">((</span><span class="s">&#39;endcomment&#39;</span><span class="p">,))</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">delete_first_token</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">CommentNode</span><span class="p">()</span>

<span class="k">class</span> <span class="nc">CommentNode</span><span class="p">(</span><span class="n">template</span><span class="o">.</span><span class="n">Node</span><span class="p">):</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="p">):</span>
        <span class="k">return</span> <span class="s">&#39;&#39;</span>
</pre></div>
</div>
<p><tt class="docutils literal"><span class="pre">parser.parse()</span></tt> takes a tuple of names of block tags ''to parse until''. It
returns an instance of <tt class="docutils literal"><span class="pre">django.template.NodeList</span></tt>, which is a list of
all <tt class="docutils literal"><span class="pre">Node</span></tt> objects that the parser encountered ''before'' it encountered
any of the tags named in the tuple.</p>
<p>In <tt class="docutils literal"><span class="pre">&quot;nodelist</span> <span class="pre">=</span> <span class="pre">parser.parse(('endcomment',))&quot;</span></tt> in the above example,
<tt class="docutils literal"><span class="pre">nodelist</span></tt> is a list of all nodes between the <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">comment</span> <span class="pre">%}</span></tt> and
<tt class="docutils literal"><span class="pre">{%</span> <span class="pre">endcomment</span> <span class="pre">%}</span></tt>, not counting <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">comment</span> <span class="pre">%}</span></tt> and <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">endcomment</span> <span class="pre">%}</span></tt>
themselves.</p>
<p>After <tt class="docutils literal"><span class="pre">parser.parse()</span></tt> is called, the parser hasn't yet &quot;consumed&quot; the
<tt class="docutils literal"><span class="pre">{%</span> <span class="pre">endcomment</span> <span class="pre">%}</span></tt> tag, so the code needs to explicitly call
<tt class="docutils literal"><span class="pre">parser.delete_first_token()</span></tt>.</p>
<p><tt class="docutils literal"><span class="pre">CommentNode.render()</span></tt> simply returns an empty string. Anything between
<tt class="docutils literal"><span class="pre">{%</span> <span class="pre">comment</span> <span class="pre">%}</span></tt> and <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">endcomment</span> <span class="pre">%}</span></tt> is ignored.</p>
</div>
<div class="section" id="s-parsing-until-another-block-tag-and-saving-contents">
<span id="parsing-until-another-block-tag-and-saving-contents"></span><h4>Parsing until another block tag, and saving contents<a class="headerlink" href="#parsing-until-another-block-tag-and-saving-contents" title="Permalink to this headline">¶</a></h4>
<p>In the previous example, <tt class="docutils literal"><span class="pre">do_comment()</span></tt> discarded everything between
<tt class="docutils literal"><span class="pre">{%</span> <span class="pre">comment</span> <span class="pre">%}</span></tt> and <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">endcomment</span> <span class="pre">%}</span></tt>. Instead of doing that, it's
possible to do something with the code between block tags.</p>
<p>For example, here's a custom template tag, <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">upper</span> <span class="pre">%}</span></tt>, that capitalizes
everything between itself and <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">endupper</span> <span class="pre">%}</span></tt>.</p>
<p>Usage:</p>
<div class="highlight-html+django"><div class="highlight"><pre><span class="cp">{%</span> <span class="k">upper</span> <span class="cp">%}</span>This will appear in uppercase, <span class="cp">{{</span> <span class="nv">your_name</span> <span class="cp">}}</span>.<span class="cp">{%</span> <span class="k">endupper</span> <span class="cp">%}</span>
</pre></div>
</div>
<p>As in the previous example, we'll use <tt class="docutils literal"><span class="pre">parser.parse()</span></tt>. But this time, we
pass the resulting <tt class="docutils literal"><span class="pre">nodelist</span></tt> to the <tt class="docutils literal"><span class="pre">Node</span></tt>:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">def</span> <span class="nf">do_upper</span><span class="p">(</span><span class="n">parser</span><span class="p">,</span> <span class="n">token</span><span class="p">):</span>
    <span class="n">nodelist</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse</span><span class="p">((</span><span class="s">&#39;endupper&#39;</span><span class="p">,))</span>
    <span class="n">parser</span><span class="o">.</span><span class="n">delete_first_token</span><span class="p">()</span>
    <span class="k">return</span> <span class="n">UpperNode</span><span class="p">(</span><span class="n">nodelist</span><span class="p">)</span>

<span class="k">class</span> <span class="nc">UpperNode</span><span class="p">(</span><span class="n">template</span><span class="o">.</span><span class="n">Node</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">nodelist</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">nodelist</span> <span class="o">=</span> <span class="n">nodelist</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="p">):</span>
        <span class="n">output</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">nodelist</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">context</span><span class="p">)</span>
        <span class="k">return</span> <span class="n">output</span><span class="o">.</span><span class="n">upper</span><span class="p">()</span>
</pre></div>
</div>
<p>The only new concept here is the <tt class="docutils literal"><span class="pre">self.nodelist.render(context)</span></tt> in
<tt class="docutils literal"><span class="pre">UpperNode.render()</span></tt>.</p>
<p>For more examples of complex rendering, see the source code for <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">if</span> <span class="pre">%}</span></tt>,
<tt class="docutils literal"><span class="pre">{%</span> <span class="pre">for</span> <span class="pre">%}</span></tt>, <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">ifequal</span> <span class="pre">%}</span></tt> and <tt class="docutils literal"><span class="pre">{%</span> <span class="pre">ifchanged</span> <span class="pre">%}</span></tt>. They live in
<tt class="docutils literal"><span class="pre">django/template/defaulttags.py</span></tt>.</p>
</div>
</div>
</div>
</div>


          </div>         
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="../contents.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="#">Custom template tags and filters</a><ul>
<li><a class="reference external" href="#introduction">Introduction</a><ul>
<li><a class="reference external" href="#code-layout">Code layout</a></li>
<li><a class="reference external" href="#writing-custom-template-filters">Writing custom template filters</a><ul>
<li><a class="reference external" href="#template-filters-that-expect-strings">Template filters that expect strings</a></li>
<li><a class="reference external" href="#registering-custom-filters">Registering custom filters</a></li>
<li><a class="reference external" href="#filters-and-auto-escaping">Filters and auto-escaping</a></li>
</ul>
</li>
<li><a class="reference external" href="#writing-custom-template-tags">Writing custom template tags</a><ul>
<li><a class="reference external" href="#a-quick-overview">A quick overview</a></li>
<li><a class="reference external" href="#writing-the-compilation-function">Writing the compilation function</a></li>
<li><a class="reference external" href="#writing-the-renderer">Writing the renderer</a></li>
<li><a class="reference external" href="#auto-escaping-considerations">Auto-escaping considerations</a></li>
<li><a class="reference external" href="#registering-the-tag">Registering the tag</a></li>
<li><a class="reference external" href="#passing-template-variables-to-the-tag">Passing template variables to the tag</a></li>
<li><a class="reference external" href="#shortcut-for-simple-tags">Shortcut for simple tags</a></li>
<li><a class="reference external" href="#inclusion-tags">Inclusion tags</a></li>
<li><a class="reference external" href="#setting-a-variable-in-the-context">Setting a variable in the context</a></li>
<li><a class="reference external" href="#parsing-until-another-block-tag">Parsing until another block tag</a></li>
<li><a class="reference external" href="#parsing-until-another-block-tag-and-saving-contents">Parsing until another block tag, and saving contents</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>

  <h3>Browse</h3>
  <ul>
    
      <li>Prev: <a href="custom-model-fields.html">Writing custom model fields</a></li>
    
    
      <li>Next: <a href="custom-file-storage.html">Writing a custom storage system</a></li>
    
  </ul>
  <h3>You are here:</h3>
  <ul>
      <li>
        <a href="../index.html">Django v1.1 documentation</a>
        
          <ul><li><a href="index.html">&#8220;How-to&#8221; guides</a>
        
        <ul><li>Custom template tags and filters</li></ul>
        </li></ul>
      </li>
  </ul>  

            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="../_sources/howto/custom-template-tags.txt"
                     rel="nofollow">Show Source</a></li>
            </ul>
          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <form class="search" action="../search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">Feb 18, 2011</p>
          </div> 
        
      
    </div>
    
    <div id="ft">
      <div class="nav">
    &laquo; <a href="custom-model-fields.html" title="Writing custom model fields">previous</a> 
     |
    <a href="index.html" title="&amp;#8220;How-to&amp;#8221; guides" accesskey="U">up</a>
   |
    <a href="custom-file-storage.html" title="Writing a custom storage system">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>