Sophie

Sophie

distrib > Mandriva > 2010.0 > i586 > media > contrib-release > by-pkgid > 5d5a53cfb1fc82fdbf1e3e9ea3253fa5 > files > 87

python-mako-0.2.4-1mdv2010.0.noarch.rpm

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
	<title>
    Mako Documentation
</title>
	
    <link rel="stylesheet" href="docs.css"></link>
    <link rel="stylesheet" href="highlight.css"></link>
    




</head>
<body>










<div id="topanchor"><a name="top">&nbsp;</a></div>

<div id="pagecontrol"><a href="index.html">Multiple Pages</a> | <a href="documentation.html">One Page</a></div>

<h1>Mako Documentation</h1>

<div class="versionheader">Version: 0.2.4   Last Updated: 12/22/08 22:46:37</div>







	<div class="topnav">

	<a name="full_index"></a>
	<h3>Table of Contents</h3>
	
	
    <ul>
        <li><A style="" href="#usage">Basic Usage</a></li>
        
            
    <ul>
        <li><A style="" href="#usage_file">Using File-Based Templates</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#usage_lookup">Using TemplateLookup</a></li>
        
            
    <ul>
        <li><A style="" href="#usage_lookup_size">Setting the Collection Size</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#usage_lookup_checks">Setting Filesystem Checks</a></li>
        
            
    <ul>
    </ul>

    </ul>

        <li><A style="" href="#usage_using">Using Unicode and Encoding</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#usage_handling">Handling Exceptions</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#usage_common">Common Framework Integrations</a></li>
        
            
    <ul>
        <li><A style="" href="#usage_common_turbogears/pylons">Turbogears/Pylons Plugin</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#usage_common_wsgi">WSGI</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#usage_common_pygments">Pygments</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#usage_common_babel">Babel (Internationalization)</a></li>
        
            
    <ul>
    </ul>

    </ul>

    </ul>

        <li><A style="" href="#syntax">Syntax</a></li>
        
            
    <ul>
        <li><A style="" href="#syntax_expression">Expression Substitution</a></li>
        
            
    <ul>
        <li><A style="" href="#syntax_expression_expression">Expression Escaping</a></li>
        
            
    <ul>
    </ul>

    </ul>

        <li><A style="" href="#syntax_control">Control Structures</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#syntax_comments">Comments</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#syntax_newline">Newline Filters</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#syntax_python">Python Blocks</a></li>
        
            
    <ul>
        <li><A style="" href="#syntax_python_module-level">Module-level Blocks</a></li>
        
            
    <ul>
    </ul>

    </ul>

        <li><A style="" href="#syntax_tags">Tags</a></li>
        
            
    <ul>
        <li><A style="" href="#syntax_tags_page"><%page></a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#syntax_tags_include"><%include></a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#syntax_tags_def"><%def></a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#syntax_tags_namespace"><%namespace></a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#syntax_tags_inherit"><%inherit></a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#syntax_tags_namespacename:defname"><%namespacename:defname></a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#syntax_tags_call"><%call></a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#syntax_tags_doc"><%doc></a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#syntax_tags_text"><%text></a></li>
        
            
    <ul>
    </ul>

    </ul>

        <li><A style="" href="#syntax_returning">Returning early from a template</a></li>
        
            
    <ul>
    </ul>

    </ul>

        <li><A style="" href="#defs">Defs</a></li>
        
            
    <ul>
        <li><A style="" href="#defs_remotedefs">Calling defs from Other Files</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#defs_programmatic">Calling defs programmatically</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#defs_nesteddefs">Defs within Defs</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#defs_defswithcontent">Calling a def with embedded content and/or other defs</a></li>
        
            
    <ul>
    </ul>

    </ul>

        <li><A style="" href="#runtime">The Mako Runtime Environment</a></li>
        
            
    <ul>
        <li><A style="" href="#runtime_context">Context</a></li>
        
            
    <ul>
        <li><A style="" href="#runtime_context_buffer">The Buffer</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#runtime_context_variables">Context Variables</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#runtime_context_accessors">Context Methods and Accessors</a></li>
        
            
    <ul>
    </ul>

    </ul>

        <li><A style="" href="#runtime_builtins">All the built-in names</a></li>
        
            
    <ul>
    </ul>

    </ul>

        <li><A style="" href="#namespaces">Namespaces</a></li>
        
            
    <ul>
        <li><A style="" href="#namespaces_howtocall">Ways to Call Namespaces</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#namespaces_frommodules">Namespaces from Regular Python Modules</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#namespaces_declaring">Declaring defs in namespaces.</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#namespaces_body">The "body()" method</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#namespaces_properties">Namespace methods and properties</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#namespaces_builtin">Built-in Namespaces</a></li>
        
            
    <ul>
        <li><A style="" href="#namespaces_builtin_local">local</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#namespaces_builtin_self">self</a></li>
        
            
    <ul>
    </ul>

    </ul>

        <li><A style="" href="#namespaces_inheritable">Inheritable Namespaces</a></li>
        
            
    <ul>
    </ul>

    </ul>

        <li><A style="" href="#inheritance">Inheritance</a></li>
        
            
    <ul>
        <li><A style="" href="#inheritance_next">Using the "next" namespace to produce content wrapping</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#inheritance_parent">Using the "parent" namespace to augment defs</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#inheritance_inheritable">Inheritable Attributes</a></li>
        
            
    <ul>
    </ul>

    </ul>

        <li><A style="" href="#filtering">Filtering and Buffering</a></li>
        
            
    <ul>
        <li><A style="" href="#filtering_expression">Expression Filtering</a></li>
        
            
    <ul>
        <li><A style="" href="#filtering_expression_defaultfilters">The default_filters Argument</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#filtering_expression_turning">Turning off Filtering with the "n" filter</a></li>
        
            
    <ul>
    </ul>

    </ul>

        <li><A style="" href="#filtering_filtering">Filtering Defs</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#filtering_buffering">Buffering</a></li>
        
            
    <ul>
    </ul>

    </ul>

        <li><A style="" href="#unicode">The Unicode Chapter</a></li>
        
            
    <ul>
        <li><A style="" href="#unicode_specifying">Specifying the Encoding of a Template File</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#unicode_handling">Handling Expressions</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#unicode_defining">Defining Output Encoding</a></li>
        
            
    <ul>
        <li><A style="" href="#unicode_defining_buffer">Buffer Selection</a></li>
        
            
    <ul>
    </ul>

    </ul>

        <li><A style="" href="#unicode_saying">Saying to Heck with it:  Disabling the usage of Unicode entirely</a></li>
        
            
    <ul>
    </ul>

    </ul>

        <li><A style="" href="#caching">Caching</a></li>
        
            
    <ul>
        <li><A style="" href="#caching_arguments">Cache arguments</a></li>
        
            
    <ul>
    </ul>

        <li><A style="" href="#caching_accessing">Accessing the Cache</a></li>
        
            
    <ul>
    </ul>

    </ul>

    </ul>


	</div>




    
    
    <A name="usage"></a>

    
    <div class="toolbar">
        <div class="prevnext">

            
            Next: <a href="#syntax">Syntax</a>
        </div>
        <h3><a href="documentation.html">Table of Contents</a></h3>
    </div>


    








    
    <A name="usage"></a>
    
    <div class="section">
    

    <h3>Basic Usage</h3>
    
    

<p>This section describes the Python API for Mako templates.  If you are using Mako within a web framework such as Pylons, the work of integrating Mako's API is already done for you, in which case you can skip to the next section, <a href="#syntax">Syntax</a>.
</p>
<p>The most basic way to create a template and render it is through the <code>Template</code> class:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="kn">from</span> <span class="nn">mako.template</span> <span class="kn">import</span> <span class="n">Template</span>

<span class="n">mytemplate</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s">&quot;hello world!&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="n">mytemplate</span><span class="o">.</span><span class="n">render</span><span class="p">()</span>
</pre></div>

    </div>
<p>Above, the text argument to <code>Template</code> is <strong>compiled</strong> into a Python module representation.  This module contains a function called <code>render_body()</code>, which produces the output of the template.  When <code>mytemplate.render()</code> is called, Mako sets up a runtime environment for the template and calls the <code>render_body()</code> function, capturing the output into a buffer and returning it's string contents.
</p>
<p>The code inside the <code>render_body()</code> function has access to a namespace of variables.  You can specify these variables by sending them as additional keyword arguments to the <code>render()</code> method:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="kn">from</span> <span class="nn">mako.template</span> <span class="kn">import</span> <span class="n">Template</span>

<span class="n">mytemplate</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s">&quot;hello, ${name}!&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="n">mytemplate</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;jack&quot;</span><span class="p">)</span>
</pre></div>

    </div>
<p>The <code>template.render()</code> method calls upon Mako to create a <code>Context</code> object, which stores all the variable names accessible to the template and also stores a buffer used to capture output.  You can create this <code>Context</code> yourself and have the template render with it, using the <code>render_context</code> method:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="kn">from</span> <span class="nn">mako.template</span> <span class="kn">import</span> <span class="n">Template</span>
<span class="kn">from</span> <span class="nn">mako.runtime</span> <span class="kn">import</span> <span class="n">Context</span>
<span class="kn">from</span> <span class="nn">StringIO</span> <span class="kn">import</span> <span class="n">StringIO</span>

<span class="n">mytemplate</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s">&quot;hello, ${name}!&quot;</span><span class="p">)</span>
<span class="n">buf</span> <span class="o">=</span> <span class="n">StringIO</span><span class="p">()</span>
<span class="n">ctx</span> <span class="o">=</span> <span class="n">Context</span><span class="p">(</span><span class="n">buf</span><span class="p">,</span> <span class="n">name</span><span class="o">=</span><span class="s">&quot;jack&quot;</span><span class="p">)</span>
<span class="n">mytemplate</span><span class="o">.</span><span class="n">render_context</span><span class="p">(</span><span class="n">ctx</span><span class="p">)</span>
<span class="k">print</span> <span class="n">buf</span><span class="o">.</span><span class="n">getvalue</span><span class="p">()</span>
</pre></div>

    </div>


    
    <A name="usage_file"></a>
    
    <div class="subsection">
    

    <h3>Using File-Based Templates</h3>
    
    

<p>A <code>Template</code> can also load its template source code from a file, using the <code>filename</code> keyword argument:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="kn">from</span> <span class="nn">mako.template</span> <span class="kn">import</span> <span class="n">Template</span>

<span class="n">mytemplate</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s">&#39;/docs/mytmpl.txt&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="n">mytemplate</span><span class="o">.</span><span class="n">render</span><span class="p">()</span>
</pre></div>

    </div>
<p>For improved performance, a <code>Template</code> which is loaded from a file can also cache the source code to its generated module on the filesystem as a regular Python module file (i.e. a .py file).  To do this, just add the <code>module_directory</code> argument to the template:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="kn">from</span> <span class="nn">mako.template</span> <span class="kn">import</span> <span class="n">Template</span>

<span class="n">mytemplate</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s">&#39;/docs/mytmpl.txt&#39;</span><span class="p">,</span> <span class="n">module_directory</span><span class="o">=</span><span class="s">&#39;/tmp/mako_modules&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="n">mytemplate</span><span class="o">.</span><span class="n">render</span><span class="p">()</span>
</pre></div>

    </div>
<p>When the above code is rendered, a file <code>/tmp/mako_modules/docs/mytmpl.txt.py</code> is created containing the source code for the module.  The next time a <code>Template</code> with the same arguments is created, this module file will be automatically re-used.
</p>



            <a href="#usage">back to section top</a>
    </div>



    
    <A name="usage_lookup"></a>
    
    <div class="subsection">
    

    <h3>Using TemplateLookup</h3>
    
    

<p>All of the examples thus far have dealt with the usage of a single <code>Template</code> object.  If the code within those templates tries to locate another template resource, it will need some way to find them, using simple URI strings.  For this need, the resolution of other templates from within a template is accomplished by the <code>TemplateLookup</code> class.   This class is constructed given a list of directories in which to search for templates, as well as keyword arguments that will be passed to the <code>Template</code> objects it creates.
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="kn">from</span> <span class="nn">mako.template</span> <span class="kn">import</span> <span class="n">Template</span>
<span class="kn">from</span> <span class="nn">mako.lookup</span> <span class="kn">import</span> <span class="n">TemplateLookup</span>

<span class="n">mylookup</span> <span class="o">=</span> <span class="n">TemplateLookup</span><span class="p">(</span><span class="n">directories</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;/docs&#39;</span><span class="p">])</span>
<span class="n">mytemplate</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s">&quot;&quot;&quot;&lt;</span><span class="si">%i</span><span class="s">nclude file=&quot;header.txt&quot;/&gt; hello world!&quot;&quot;&quot;</span><span class="p">,</span> <span class="n">lookup</span><span class="o">=</span><span class="n">mylookup</span><span class="p">)</span>
</pre></div>

    </div>
<p>Above, we created a textual template which includes the file <code>header.txt</code>.  In order for it to have somewhere to look for <code>header.txt</code>, we passed a <code>TemplateLookup</code> object to it, which will search in the directory <code>/docs</code> for the file <code>header.txt</code>.
</p>
<p>Usually, an application will store most or all of its templates as text files on the filesystem.  So far, all of our examples have been a little bit contrived in order to illustrate the basic concepts.  But a real application would get most or all of its templates directly from the <code>TemplateLookup</code>, using the aptly named <code>get_template</code> method, which accepts the URI of the desired template:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="kn">from</span> <span class="nn">mako.template</span> <span class="kn">import</span> <span class="n">Template</span>
<span class="kn">from</span> <span class="nn">mako.lookup</span> <span class="kn">import</span> <span class="n">TemplateLookup</span>

<span class="n">mylookup</span> <span class="o">=</span> <span class="n">TemplateLookup</span><span class="p">(</span><span class="n">directories</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;/docs&#39;</span><span class="p">],</span> <span class="n">module_directory</span><span class="o">=</span><span class="s">&#39;/tmp/mako_modules&#39;</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">serve_template</span><span class="p">(</span><span class="n">templatename</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
    <span class="n">mytemplate</span> <span class="o">=</span> <span class="n">mylookup</span><span class="o">.</span><span class="n">get_template</span><span class="p">(</span><span class="n">templatename</span><span class="p">)</span>
    <span class="k">print</span> <span class="n">mytemplate</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
</pre></div>

    </div>
<p>In the example above, we create a <code>TemplateLookup</code> which will look for templates in the <code>/docs</code> directory, and will store generated module files in the <code>/tmp/mako_modules</code> directory.  The lookup locates templates by appending the given URI to each of its search directories; so if you gave it a URI of <code>/etc/beans/info.txt</code>, it would search for the file <code>/docs/etc/beans/info.txt</code>, else raise a <code>TopLevelNotFound</code> exception, which is a custom Mako exception.
</p>
<p>When the lookup locates templates, it will also assign a <code>uri</code> property to the <code>Template</code> which is the uri passed to the <code>get_template()</code> call.  <code>Template</code> uses this uri to calculate the name of its module file.  So in the above example, a <code>templatename</code> argument of <code>/etc/beans/info.txt</code> will create a module file <code>/tmp/mako_modules/etc/beans/info.txt.py</code>.
</p>


    
    <A name="usage_lookup_size"></a>
    
    <div class="subsection">
    

    <h3>Setting the Collection Size</h3>
    
    

<p>The <code>TemplateLookup</code> also serves the important need of caching a fixed set of templates in memory at a given time, so that successive uri lookups do not result in full template compilations and/or module reloads on each request.  By default, the <code>TemplateLookup</code> size is unbounded.  You can specify a fixed size using the <code>collection_size</code> argument:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="n">mylookup</span> <span class="o">=</span> <span class="n">TemplateLookup</span><span class="p">(</span><span class="n">directories</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;/docs&#39;</span><span class="p">],</span> 
                <span class="n">module_directory</span><span class="o">=</span><span class="s">&#39;/tmp/mako_modules&#39;</span><span class="p">,</span> <span class="n">collection_size</span><span class="o">=</span><span class="mf">500</span><span class="p">)</span>
</pre></div>

    </div>
<p>The above lookup will continue to load templates into memory until it reaches a count of around 500.  At that point, it will clean out a certain percentage of templates using a <strong>least recently used</strong> scheme.
</p>



            <a href="#usage">back to section top</a>
    </div>



    
    <A name="usage_lookup_checks"></a>
    
    <div class="subsection">
    

    <h3>Setting Filesystem Checks</h3>
    
    

<p>Another important flag on <code>TemplateLookup</code> is <code>filesystem_checks</code>.  This defaults to <code>True</code>, and says that each time a template is returned by the <code>get_template()</code> method, the revision time of the original template file is checked against the last time the template was loaded, and if the file is newer will reload its contents and recompile the template.  On a production system, seting <code>filesystem_checks</code> to <code>False</code> can afford a small to moderate performance increase (depending on the type of filesystem used).
</p>



    </div>




            <a href="#usage">back to section top</a>
    </div>



    
    <A name="usage_using"></a>
    
    <div class="subsection">
    

    <h3>Using Unicode and Encoding</h3>
    
    

<p>Both <code>Template</code> and <code>TemplateLookup</code> accept <code>output_encoding</code> and <code>encoding_errors</code> parameters which can be used to encode the output in any Python supported codec:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="kn">from</span> <span class="nn">mako.template</span> <span class="kn">import</span> <span class="n">Template</span>
<span class="kn">from</span> <span class="nn">mako.lookup</span> <span class="kn">import</span> <span class="n">TemplateLookup</span>

<span class="n">mylookup</span> <span class="o">=</span> <span class="n">TemplateLookup</span><span class="p">(</span><span class="n">directories</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;/docs&#39;</span><span class="p">],</span> <span class="n">output_encoding</span><span class="o">=</span><span class="s">&#39;utf-8&#39;</span><span class="p">,</span> <span class="n">encoding_errors</span><span class="o">=</span><span class="s">&#39;replace&#39;</span><span class="p">)</span>

<span class="n">mytemplate</span> <span class="o">=</span> <span class="n">mylookup</span><span class="o">.</span><span class="n">get_template</span><span class="p">(</span><span class="s">&quot;foo.txt&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="n">mytemplate</span><span class="o">.</span><span class="n">render</span><span class="p">()</span>
</pre></div>

    </div>
<p>Additionally, the <code>render_unicode()</code> method exists which will return the template output as a Python <code>unicode</code> object:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="k">print</span> <span class="n">mytemplate</span><span class="o">.</span><span class="n">render_unicode</span><span class="p">()</span>
</pre></div>

    </div>
<p>The above method disgards the output encoding keyword argument; you can encode yourself by saying:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="k">print</span> <span class="n">mytemplate</span><span class="o">.</span><span class="n">render_unicode</span><span class="p">()</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s">&#39;utf-8&#39;</span><span class="p">,</span> <span class="s">&#39;replace&#39;</span><span class="p">)</span>
</pre></div>

    </div>
<p>Note that Mako's ability to return data in any encoding and/or <code>unicode</code> implies that the underlying output stream of the template is a Python unicode object.  This behavior is described fully in <a href="#unicode">The Unicode Chapter</a>.
</p>



            <a href="#usage">back to section top</a>
    </div>



    
    <A name="usage_handling"></a>
    
    <div class="subsection">
    

    <h3>Handling Exceptions</h3>
    
    

<p>Template exceptions can occur in two distinct places.  One is when you <strong>lookup, parse and compile</strong> the template, the other is when you <strong>run</strong> the template.  Within the running of a template, exceptions are thrown normally from whatever Python code originated the issue.  Mako has its own set of exception classes which mostly apply to the lookup and lexer/compiler stages of template construction.  Mako provides some library routines that can be used to help provide Mako-specific information about any exception's stack trace, as well as formatting the exception within textual or HTML format.  In all cases, the main value of these handlers is that of converting Python filenames, line numbers, and code samples into Mako template filenames, line numbers, and code samples.  All lines within a stack trace which correspond to a Mako template module will be converted to be against the originating template file.
</p>
<p>To format exception traces, the <code>text_error_template</code> and <code>html_error_template</code> functions are provided.  They make usage of <code>sys.exc_info()</code> to get at the most recently thrown exception.  Usage of these handlers usually looks like:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="kn">from</span> <span class="nn">mako</span> <span class="kn">import</span> <span class="n">exceptions</span>

<span class="k">try</span><span class="p">:</span>
    <span class="n">template</span> <span class="o">=</span> <span class="n">lookup</span><span class="o">.</span><span class="n">get_template</span><span class="p">(</span><span class="n">uri</span><span class="p">)</span>
    <span class="k">print</span> <span class="n">template</span><span class="o">.</span><span class="n">render</span><span class="p">()</span>
<span class="k">except</span><span class="p">:</span>
    <span class="k">print</span> <span class="n">exceptions</span><span class="o">.</span><span class="n">text_error_template</span><span class="p">()</span><span class="o">.</span><span class="n">render</span><span class="p">()</span>
</pre></div>

    </div>
<p>Or for the HTML render function:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="kn">from</span> <span class="nn">mako</span> <span class="kn">import</span> <span class="n">exceptions</span>

<span class="k">try</span><span class="p">:</span>
    <span class="n">template</span> <span class="o">=</span> <span class="n">lookup</span><span class="o">.</span><span class="n">get_template</span><span class="p">(</span><span class="n">uri</span><span class="p">)</span>
    <span class="k">print</span> <span class="n">template</span><span class="o">.</span><span class="n">render</span><span class="p">()</span>
<span class="k">except</span><span class="p">:</span>
    <span class="k">print</span> <span class="n">exceptions</span><span class="o">.</span><span class="n">html_error_template</span><span class="p">()</span><span class="o">.</span><span class="n">render</span><span class="p">()</span>
</pre></div>

    </div>
<p>The <code>html_error_template</code> template accepts two options: specifying <code>full=False</code> causes only a section of an HTML document to be rendered. Specifying <code>css=False</code> will disable the default stylesheet from being rendered.
</p>
<p>E.g.:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre>    print exceptions.html_error_template().render(full=False)
</pre></div>

    </div>
<p>The HTML render function is also available built-in to <code>Template</code> using the <code>format_exceptions</code> flag.  In this case, any exceptions raised within the <strong>render</strong> stage of the template will result in the output being substituted with the output of <code>html_error_template</code>.
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="n">template</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="n">filename</span><span class="o">=</span><span class="s">&quot;/foo/bar&quot;</span><span class="p">,</span> <span class="n">format_exceptions</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">print</span> <span class="n">template</span><span class="o">.</span><span class="n">render</span><span class="p">()</span>
</pre></div>

    </div>
<p>Note that the compile stage of the above template occurs when you construct the <code>Template</code> itself, and no output stream is defined.  Therefore exceptions which occur within the lookup/parse/compile stage will not be handled and will propagate normally.   While the pre-render traceback usually will not include any Mako-specific lines anyway, it will mean that exceptions which occur previous to rendering and those which occur within rendering will be handled differently...so the <code>try/except</code> patterns described previously are probably of more general use.
</p>
<p>The underlying object used by the error template functions is the <code>RichTraceback</code> object.  This object can also be used directly to provide custom error views.  Here's an example usage which describes its general API:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="kn">from</span> <span class="nn">mako.exceptions</span> <span class="kn">import</span> <span class="n">RichTraceback</span>

<span class="k">try</span><span class="p">:</span>
    <span class="n">template</span> <span class="o">=</span> <span class="n">lookup</span><span class="o">.</span><span class="n">get_template</span><span class="p">(</span><span class="n">uri</span><span class="p">)</span>
    <span class="k">print</span> <span class="n">template</span><span class="o">.</span><span class="n">render</span><span class="p">()</span>
<span class="k">except</span><span class="p">:</span>
    <span class="n">traceback</span> <span class="o">=</span> <span class="n">RichTraceback</span><span class="p">()</span>
    <span class="k">for</span> <span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">lineno</span><span class="p">,</span> <span class="n">function</span><span class="p">,</span> <span class="n">line</span><span class="p">)</span> <span class="ow">in</span> <span class="n">traceback</span><span class="o">.</span><span class="n">traceback</span><span class="p">:</span>
        <span class="k">print</span> <span class="s">&quot;File </span><span class="si">%s</span><span class="s">, line </span><span class="si">%s</span><span class="s">, in </span><span class="si">%s</span><span class="s">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="n">filename</span><span class="p">,</span> <span class="n">lineno</span><span class="p">,</span> <span class="n">function</span><span class="p">)</span>
        <span class="k">print</span> <span class="n">line</span><span class="p">,</span> <span class="s">&quot;</span><span class="se">\n</span><span class="s">&quot;</span>
    <span class="k">print</span> <span class="s">&quot;</span><span class="si">%s</span><span class="s">: </span><span class="si">%s</span><span class="s">&quot;</span> <span class="o">%</span> <span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">traceback</span><span class="o">.</span><span class="n">error</span><span class="o">.</span><span class="n">__class__</span><span class="o">.</span><span class="n">__name__</span><span class="p">),</span> <span class="n">traceback</span><span class="o">.</span><span class="n">error</span><span class="p">)</span>
</pre></div>

    </div>
<p>Further information about <code>RichTraceback</code> is available within the module-level documentation for <code>mako.exceptions</code>.
</p>



            <a href="#usage">back to section top</a>
    </div>



    
    <A name="usage_common"></a>
    
    <div class="subsection">
    

    <h3>Common Framework Integrations</h3>
    
    

<p>The Mako distribution includes a little bit of helper code for the purpose of using Mako in some popular web framework scenarios.  This is a brief description of whats included.
</p>


    
    <A name="usage_common_turbogears/pylons"></a>
    
    <div class="subsection">
    

    <h3>Turbogears/Pylons Plugin</h3>
    
    

<p>The standard plugin methodology used by <a href='http://www.turbogears.org'>Turbogears</a> as well as <a href='http://www.pylonshq.com'>Pylons</a> is included in the module <code>mako.ext.turbogears</code>, using the <code>TGPlugin</code> class.  This is also a setuptools entrypoint under the heading <code>python.templating.engines</code> with the name <code>mako</code>.
</p>



            <a href="#usage">back to section top</a>
    </div>



    
    <A name="usage_common_wsgi"></a>
    
    <div class="subsection">
    

    <h3>WSGI</h3>
    
    

<p>A sample WSGI application is included in the distrubution in the file <code>examples/wsgi/run_wsgi.py</code>.  This runner is set up to pull files from a <code>templates</code> as well as an <code>htdocs</code> directory and includes a rudimental two-file layout.  The WSGI runner acts as a fully functional standalone web server, using <code>wsgiutils</code> to run itself, and propagates GET and POST arguments from the request into the <code>Context</code>, can serve images, css files and other kinds of files, and also displays errors using Mako's included exception-handling utilities.
</p>



            <a href="#usage">back to section top</a>
    </div>



    
    <A name="usage_common_pygments"></a>
    
    <div class="subsection">
    

    <h3>Pygments</h3>
    
    

<p>A <a href='http://pygments.pocoo.org'>Pygments</a>-compatible syntax highlighting module is included under <code>mako.ext.pygmentplugin</code>.  This module is used in the generation of Mako documentation and also contains various setuptools entry points under the heading <code>pygments.lexers</code>, including <code>mako</code>, <code>html+mako</code>, <code>xml+mako</code> (see the <code>setup.py</code> file for all the entry points).
</p>



            <a href="#usage">back to section top</a>
    </div>



    
    <A name="usage_common_babel"></a>
    
    <div class="subsection">
    

    <h3>Babel (Internationalization)</h3>
    
    

<p>Mako provides support for extracting gettext messages from templates via a <a href='http://babel.edgewall.org/'>Babel</a> extractor entry point under <code>mako.ext.babelplugin</code>.
</p>
<p>Gettext messages are extracted from all Python code sections, even the more obscure ones such as <a href="#syntax_control">control structures</a>, <a href="#defs">def tag function declarations</a>, <a href="#defs_defswithcontent">call tag exprs</a> and even <a href="#syntax_tags_page">page tag args</a>.
</p>
<p><a href='http://babel.edgewall.org/wiki/Documentation/messages.html#comments-tags-and-translator-comments-explanation'>Translator comments</a> may also be extracted from Mako templates when a comment tag is specified to <a href='http://babel.edgewall.org/'>Babel</a> (such as with the -c option).
</p>
<p>For example, a project '<code>myproj</code>' contains the following Mako template at myproj/myproj/templates/name.html:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;name&quot;</span><span class="nt">&gt;</span>
  Name:
  ## TRANSLATORS: This is a proper name. See the gettext
  ## manual, section Names.
  <span class="cp">${</span><span class="n">_</span><span class="p">(</span><span class="s">&#39;Francois Pinard&#39;</span><span class="p">)</span><span class="cp">}</span>
<span class="nt">&lt;/div&gt;</span>
</pre></div>

    </div>
<p>To extract gettext messages from this template the project needs a Mako section in its <a href='http://babel.edgewall.org/wiki/Documentation/messages.html#extraction-method-mapping-and-configuration'>Babel Extraction Method Mapping file</a> (typically located at myproj/babel.cfg):
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="c"># Extraction from Python source files</span>

<span class="k">[python: myproj/**.py]</span>

<span class="c"># Extraction from Mako templates</span>

<span class="k">[mako: myproj/templates/**.html]</span>
<span class="na">input_encoding</span> <span class="o">=</span> <span class="s">utf-8</span>
</pre></div>

    </div>
<p>The Mako extractor supports an optional <code>input_encoding</code> parameter specifying the encoding of the templates (identical to <code>Template</code>/<code>TemplateLookup</code>'s <code>input_encoding</code> parameter).
</p>
<p>Invoking <a href='http://babel.edgewall.org/'>Babel</a>'s extractor at the command line in the project's root directory:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre>myproj$ pybabel extract -F babel.cfg -c &quot;TRANSLATORS:&quot; .
</pre></div>

    </div>
<p>Will output a gettext catalog to stdout including the following:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre>#. TRANSLATORS: This is a proper name. See the gettext
#. manual, section Names.
#: myproj/templates/name.html:5
msgid &quot;Francois Pinard&quot;
msgstr &quot;&quot;
</pre></div>

    </div>
<p>This is only a basic example: <a href='http://babel.edgewall.org/'>Babel</a> can be invoked from setup.py and its command line options specified in the accompanying setup.cfg via <a href='http://babel.edgewall.org/wiki/Documentation/setup.html'>Babel Distutils/Setuptools Integration</a>.
</p>
<p>Comments must immediately precede a gettext message to be extracted. In the following case the TRANSLATORS: comment would not have been extracted:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">&quot;name&quot;</span><span class="nt">&gt;</span>
  ## TRANSLATORS: This is a proper name. See the gettext
  ## manual, section Names.
  Name: <span class="cp">${</span><span class="n">_</span><span class="p">(</span><span class="s">&#39;Francois Pinard&#39;</span><span class="p">)</span><span class="cp">}</span>
<span class="nt">&lt;/div&gt;</span>
</pre></div>

    </div>
<p>See the <a href='http://babel.edgewall.org/wiki/Documentation/index.html'>Babel User Guide</a> for more information.
</p>




    </div>




    </div>




            <a href="#usage">back to section top</a>
    </div>


</html>
    
    
    <A name="syntax"></a>

    
    <div class="toolbar">
        <div class="prevnext">
            Previous: <a href="#usage">Basic Usage</a>

            |
            Next: <a href="#defs">Defs</a>
        </div>
        <h3><a href="documentation.html">Table of Contents</a></h3>
    </div>


    








    
    <A name="syntax"></a>
    
    <div class="section">
    

    <h3>Syntax</h3>
    
    

<p>A Mako template is parsed from a text stream containing any kind of content, XML, HTML, email text, etc.  The template can further contain Mako-specific directives which represent variable and/or expression substitutions, control structures (i.e. conditionals and loops), server-side comments, full blocks of Python code, as well as various tags that offer additional functionality.  All of these constructs compile into real Python code.  This means that you can leverage the full power of Python in almost every aspect of a Mako template.
</p>


    
    <A name="syntax_expression"></a>
    
    <div class="subsection">
    

    <h3>Expression Substitution</h3>
    
    

<p>The simplest expression is just a variable substitution.  The syntax for this is the <code>${}</code> construct, which is inspired by Perl, Genshi, JSP EL, and others:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre>this is x: <span class="cp">${</span><span class="n">x</span><span class="cp">}</span>
</pre></div>

    </div>
<p>Above, the string representation of <code>x</code> is applied to the template's output stream.  If you're wondering where <code>x</code> comes from, its usually from the <code>Context</code> supplied to the template's rendering function.  If <code>x</code> was not supplied to the template and was not otherwise assigned locally, it evaluates to a special value <code>UNDEFINED</code>.  More on that later.
</p>
<p>The contents within the <code>${}</code> tag are evaluated by Python directly, so full expressions are OK:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre>pythagorean theorem:  <span class="cp">${</span><span class="nb">pow</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="mf">2</span><span class="p">)</span> <span class="o">+</span> <span class="nb">pow</span><span class="p">(</span><span class="n">y</span><span class="p">,</span><span class="mf">2</span><span class="p">)</span><span class="cp">}</span>
</pre></div>

    </div>
<p>The results of the expression are evaluated into a string result in all cases before being rendered to the output stream, such as the above example where the expression produces a numeric result.
</p>


    
    <A name="syntax_expression_expression"></a>
    
    <div class="subsection">
    

    <h3>Expression Escaping</h3>
    
    

<p>Mako includes a number of built-in escaping mechanisms, including HTML, URI and XML escaping, as well as a "trim" function.  These escapes can be added to an expression substituion using the <code>|</code> operator:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="s">&quot;this is some text&quot;</span> <span class="o">|</span> <span class="n">u</span><span class="cp">}</span>
</pre></div>

    </div>
<p>The above expression applies URL escaping to the expression, and produces <code>this+is+some+text</code>.  The <code>u</code> name indicates URL escaping, whereas <code>h</code> represents HTML escaping, <code>x</code> represents XML escaping, and <code>trim</code> applies a trim function.
</p>
<p>Read more about built in filtering functions, including how to make your own filter functions, in <a href="#filtering">Filtering and Buffering</a>.
</p>



    </div>




            <a href="#syntax">back to section top</a>
    </div>



    
    <A name="syntax_control"></a>
    
    <div class="subsection">
    

    <h3>Control Structures</h3>
    
    

<p>A control structure refers to all those things that control the flow of a program - conditionals (i.e. if/else), loops (like while and for), as well as things like <code>try/except</code>.  In Mako, control structures are written using the <code>%</code> marker followed by a regular Python control expression, and are "closed" by using another <code>%</code> marker with the tag "<code>end&lt;name&gt;</code>", where "<code>&lt;name&gt;</code>" is the keyword of the expression:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">%</span> <span class="k">if</span> <span class="n">x</span><span class="o">==</span><span class="mf">5</span><span class="p">:</span>
    this is some output
<span class="cp">%</span><span class="k"> endif</span>
</pre></div>

    </div>
<p>The <code>%</code> can appear anywhere on the line as long as no text precedes it; indentation is not signficant.  The full range of Python "colon" expressions are allowed here, including <code>if/elif/else</code>, <code>while</code>, <code>for</code>, and even <code>def</code>, although Mako has a built-in tag for defs which is more full-featured.
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">%</span> <span class="k">for</span> <span class="n">a</span> <span class="ow">in</span> <span class="p">[</span><span class="s">&#39;one&#39;</span><span class="p">,</span> <span class="s">&#39;two&#39;</span><span class="p">,</span> <span class="s">&#39;three&#39;</span><span class="p">,</span> <span class="s">&#39;four&#39;</span><span class="p">,</span> <span class="s">&#39;five&#39;</span><span class="p">]:</span>
    <span class="cp">%</span> <span class="k">if</span> <span class="n">a</span><span class="p">[</span><span class="mf">0</span><span class="p">]</span> <span class="o">==</span> <span class="s">&#39;t&#39;</span><span class="p">:</span>
     its two or three
    <span class="cp">%</span> <span class="k">elif</span> <span class="n">a</span><span class="p">[</span><span class="mf">0</span><span class="p">]</span> <span class="o">==</span> <span class="s">&#39;f&#39;</span><span class="p">:</span>
    four/five
    <span class="cp">%</span> <span class="k">else</span><span class="p">:</span>
    one
    <span class="cp">%</span><span class="k">endif</span>
<span class="cp">%</span><span class="k"> endfor</span>
</pre></div>

    </div>



            <a href="#syntax">back to section top</a>
    </div>



    
    <A name="syntax_comments"></a>
    
    <div class="subsection">
    

    <h3>Comments</h3>
    
    

<p>Comments come in two varieties.  The single line comment uses <code>##</code> as the first non-space characters on a line:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">## this is a comment.</span>
...text ...
</pre></div>

    </div>
<p>A multiline version exists using <code>&lt;%doc&gt;  ...text... &lt;/%doc&gt;</code>:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%doc&gt;</span>
<span class="cp">    these are comments</span>
<span class="cp">    more comments</span>
<span class="cp">&lt;/%doc&gt;</span>
</pre></div>

    </div>
<p>Note that this is <strong>new behavior as of Mako 0.1.3</strong>.  The syntax prior to this version was the single pound sign (<code>#</code>), which was agreed by the Mako userbase that it conflicted with CSS elements too often and also did not address multiline comments easily.
</p>



            <a href="#syntax">back to section top</a>
    </div>



    
    <A name="syntax_newline"></a>
    
    <div class="subsection">
    

    <h3>Newline Filters</h3>
    
    

<p>The backslash ("<code>\</code>") character, placed at the end of any line, will consume the newline character before continuing to the next line:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre>here is a line that goes onto <span class="o">\</span>
another line.
</pre></div>

    </div>
<p>The above text evaluates to:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre>here is a line that goes onto another line.
</pre></div>

    </div>



            <a href="#syntax">back to section top</a>
    </div>



    
    <A name="syntax_python"></a>
    
    <div class="subsection">
    

    <h3>Python Blocks</h3>
    
    

<p>Any arbitrary block of python can be dropped in using the <code>&lt;% %&gt;</code> tags:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre>this is a template
<span class="cp">&lt;%</span>
    <span class="n">x</span> <span class="o">=</span> <span class="n">db</span><span class="o">.</span><span class="n">get_resource</span><span class="p">(</span><span class="s">&#39;foo&#39;</span><span class="p">)</span>
    <span class="n">y</span> <span class="o">=</span> <span class="p">[</span><span class="n">z</span><span class="o">.</span><span class="n">element</span> <span class="k">for</span> <span class="n">z</span> <span class="ow">in</span> <span class="n">x</span> <span class="k">if</span> <span class="n">x</span><span class="o">.</span><span class="n">frobnizzle</span><span class="o">==</span><span class="mf">5</span><span class="p">]</span>
<span class="cp">%&gt;</span>
<span class="cp">%</span> <span class="k">for</span> <span class="n">elem</span> <span class="ow">in</span> <span class="n">y</span><span class="p">:</span>
    element: <span class="cp">${</span><span class="n">elem</span><span class="cp">}</span>
<span class="cp">%</span><span class="k"> endfor</span>
</pre></div>

    </div>
<p>Within <code>&lt;% %&gt;</code>, you're writing a regular block of Python code.  While the code can appear with an arbitrary level of preceding whitespace,  it has to be consistently formatted with itself.  Mako's compiler will adjust the block of Python to be consistent with the surrounding generated Python code.
</p>


    
    <A name="syntax_python_module-level"></a>
    
    <div class="subsection">
    

    <h3>Module-level Blocks</h3>
    
    

<p>A variant on <code>&lt;% %&gt;</code> is the module-level code block, denoted by <code>&lt;%! %&gt;</code>.  Code within these tags is executed at the module level of the template, and not within the rendering function of the template.  Therefore, this code does not have access to the template's context and is only executed when the template is loaded into memory (which can be only once per application, or more, depending on the runtime environment).  Use the <code>&lt;%! %&gt;</code> tags to declare your template's imports, as well as any pure-Python functions you might want to declare:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%!</span>
    <span class="kn">import</span> <span class="nn">mylib</span>
    <span class="kn">import</span> <span class="nn">re</span>

    <span class="k">def</span> <span class="nf">filter</span><span class="p">(</span><span class="n">text</span><span class="p">):</span>
        <span class="k">return</span> <span class="n">re</span><span class="o">.</span><span class="n">sub</span><span class="p">(</span><span class="s">r&#39;^@&#39;</span><span class="p">,</span> <span class="s">&#39;&#39;</span><span class="p">,</span> <span class="n">text</span><span class="p">)</span>
<span class="cp">%&gt;</span>
</pre></div>

    </div>
<p>Any number of <code>&lt;%! %&gt;</code> blocks can be declared anywhere in a template; they will be rendered in the resulting module in the order that they appear.
</p>



    </div>




            <a href="#syntax">back to section top</a>
    </div>



    
    <A name="syntax_tags"></a>
    
    <div class="subsection">
    

    <h3>Tags</h3>
    
    

<p>The rest of what Mako offers takes place in the form of tags.  All tags use the same syntax, which is similar to an XML tag except that the first character of the tag name is a <code>%</code> character.  The tag is closed either by a contained slash character, or an explicit closing tag:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">include</span> <span class="na">file=</span><span class="s">&quot;foo.txt&quot;</span><span class="cp">/&gt;</span>

<span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;foo&quot;</span> <span class="na">buffered=</span><span class="s">&quot;True&quot;</span><span class="cp">&gt;</span>
    this is a def
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>All tags have a set of attributes which are defined for each tag.  Some of these attributes are required.  Also, many attributes support <strong>evaluation</strong>, meaning you can embed an expression (using <code>${}</code>) inside the attribute text:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">include</span> <span class="na">file=</span><span class="s">&quot;/foo/bar/${myfile}.txt&quot;</span><span class="cp">/&gt;</span>
</pre></div>

    </div>
<p>Whether or not an attribute accepts runtime evaluation depends on the type of tag and how that tag is compiled into the template.  The best way to find out if you can stick an expression in is to try it !  The lexer will tell you if its not valid.
</p>
<p>Heres a quick summary of all the tags:
</p>


    
    <A name="syntax_tags_page"></a>
    
    <div class="subsection">
    

    <h3><%page></h3>
    
    

<p>This tag defines general characteristics of the template, including caching arguments, and optional lists of arguments which the template expects when invoked.
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">page</span> <span class="na">args=</span><span class="s">&quot;x, y, z=&#39;default&#39;&quot;</span><span class="cp">/&gt;</span>
</pre></div>

    </div>
<p>Or a page tag that defines caching characteristics:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">page</span> <span class="na">cached=</span><span class="s">&quot;True&quot;</span> <span class="na">cache_type=</span><span class="s">&quot;memory&quot;</span><span class="cp">/&gt;</span>
</pre></div>

    </div>
<p>Currently, only one <code>&lt;%page&gt;</code> tag gets used per template, the rest get ignored.  While this will be improved in a future release, for now make sure you have only one <code>&lt;%page&gt;</code> tag defined in your template, else you may not get the results you want.  The details of what <code>&lt;%page&gt;</code> is used for are described further in <a href="#namespaces_body">The "body()" method</a> as well as <a href="#caching">Caching</a>.
</p>



            <a href="#syntax">back to section top</a>
    </div>



    
    <A name="syntax_tags_include"></a>
    
    <div class="subsection">
    

    <h3><%include></h3>
    
    

<p>A tag that is familiar from other template languages, %include is a regular joe that just accepts a file argument and calls in the rendered result of that file:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">include</span> <span class="na">file=</span><span class="s">&quot;header.html&quot;</span><span class="cp">/&gt;</span>

    hello world

<span class="cp">&lt;%</span><span class="nb">include</span> <span class="na">file=</span><span class="s">&quot;footer.html&quot;</span><span class="cp">/&gt;</span>
</pre></div>

    </div>
<p>Include also accepts arguments which are available as <code>&lt;%page&gt;</code> arguments in the receiving template:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">include</span> <span class="na">file=</span><span class="s">&quot;toolbar.html&quot;</span> <span class="na">args=</span><span class="s">&quot;current_section=&#39;members&#39;, username=&#39;ed&#39;&quot;</span><span class="cp">/&gt;</span>
</pre></div>

    </div>



            <a href="#syntax">back to section top</a>
    </div>



    
    <A name="syntax_tags_def"></a>
    
    <div class="subsection">
    

    <h3><%def></h3>
    
    

<p>The <code>%def</code> tag defines a Python function which contains a set of content, that can be called at some other point in the template.  The basic idea is simple:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;myfunc(x)&quot;</span><span class="cp">&gt;</span>
    this is myfunc, x is <span class="cp">${</span><span class="n">x</span><span class="cp">}</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>

<span class="cp">${</span><span class="n">myfunc</span><span class="p">(</span><span class="mf">7</span><span class="p">)</span><span class="cp">}</span>
</pre></div>

    </div>
<p>The %def tag is a lot more powerful than a plain Python def, as the Mako compiler provides many extra services with %def that you wouldn't normally have, such as the ability to export defs as template "methods", automatic propigation of the current <code>Context</code>, buffering/filtering/caching flags, and def calls with content, which enable packages of defs to be sent as arguments to other def calls (not as hard as it sounds).  Get the full deal on what %def can do in <a href="#defs">Defs</a>.
</p>



            <a href="#syntax">back to section top</a>
    </div>



    
    <A name="syntax_tags_namespace"></a>
    
    <div class="subsection">
    

    <h3><%namespace></h3>
    
    

<p>%namespace is Mako's equivalent of Python's <code>import</code> statement.  It allows access to all the rendering functions and metadata of other template files, plain Python modules, as well as locally defined "packages" of functions.
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">namespace</span> <span class="na">file=</span><span class="s">&quot;functions.html&quot;</span> <span class="na">import=</span><span class="s">&quot;*&quot;</span><span class="cp">/&gt;</span>
</pre></div>

    </div>
<p>The underlying object generated by %namespace, an instance of <code>mako.runtime.Namespace</code>, is a central construct used in templates to reference template-specific information such as the current URI, inheritance structures, and other things that are not as hard as they sound right here.  Namespaces are described in <a href="#namespaces">Namespaces</a>.
</p>



            <a href="#syntax">back to section top</a>
    </div>



    
    <A name="syntax_tags_inherit"></a>
    
    <div class="subsection">
    

    <h3><%inherit></h3>
    
    

<p>Inherit allows templates to arrange themselves in <strong>inheritance chains</strong>.  This is a concept familiar in many other template languages.
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">inherit</span> <span class="na">file=</span><span class="s">&quot;base.html&quot;</span><span class="cp">/&gt;</span>
</pre></div>

    </div>
<p>When using the %inherit tag, control is passed to the topmost inherited template first, which then decides how to handle calling areas of content from its inheriting templates.  Mako offers a lot of flexbility in this area, including dynamic inheritance, content wrapping, and polymorphic method calls.  Check it out in <a href="#inheritance">Inheritance</a>.
</p>



            <a href="#syntax">back to section top</a>
    </div>



    
    <A name="syntax_tags_namespacename:defname"></a>
    
    <div class="subsection">
    

    <h3><%namespacename:defname></h3>
    
    

<p>As of Mako 0.2.3, any user-defined "tag" can be created against a namespace by using a tag with a name of the form <em>namespacename</em>:<em>defname</em>.  The closed and open formats of such a tag are equivalent to an inline expression and the <code>&lt;%call&gt;</code> tag, respectively.
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">mynamespace:somedef</span> <span class="na">param=</span><span class="s">&quot;some value&quot;</span><span class="cp">&gt;</span>
    this is the body
<span class="cp">&lt;/%</span><span class="nb">mynamespace:somedef</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>To create custom tags which accept a body, see <a href="#defs_defswithcontent">Calling a def with embedded content and/or other defs</a>.
</p>



            <a href="#syntax">back to section top</a>
    </div>



    
    <A name="syntax_tags_call"></a>
    
    <div class="subsection">
    

    <h3><%call></h3>
    
    

<p>The call tag is the "classic" form of a user-defined tag, and is roughly equiavlent to the <code>&lt;%namespacename:defname&gt;</code> syntax described above.  This tag is also described in <a href="#defs_defswithcontent">Calling a def with embedded content and/or other defs</a>.
</p>



            <a href="#syntax">back to section top</a>
    </div>



    
    <A name="syntax_tags_doc"></a>
    
    <div class="subsection">
    

    <h3><%doc></h3>
    
    

<p>The doc tag handles multiline comments:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%doc&gt;</span>
<span class="cp">    these are comments</span>
<span class="cp">    more comments</span>
<span class="cp">&lt;/%doc&gt;</span>
</pre></div>

    </div>
<p>Also the <code>##</code> symbol as the first non-space characters on a line can be used for single line comments.
</p>



            <a href="#syntax">back to section top</a>
    </div>



    
    <A name="syntax_tags_text"></a>
    
    <div class="subsection">
    

    <h3><%text></h3>
    
    

<p>This tag suspends the Mako lexer's normal parsing of Mako template directives, and returns its entire body contents as plain text.  It is used pretty much to write documentation about Mako:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">text</span> <span class="na">filter=</span><span class="s">&quot;h&quot;</span><span class="cp">&gt;</span>
    heres some fake mako <span class="cp">${</span><span class="n">syntax</span><span class="cp">}</span>
    <span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;x()&quot;</span><span class="cp">&gt;${</span><span class="n">x</span><span class="cp">}&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
<span class="cp">&lt;/%</span><span class="nb">text</span><span class="cp">&gt;</span>
</pre></div>

    </div>



    </div>




            <a href="#syntax">back to section top</a>
    </div>



    
    <A name="syntax_returning"></a>
    
    <div class="subsection">
    

    <h3>Returning early from a template</h3>
    
    

<p>Sometimes you want to stop processing a template or <code>&lt;%def&gt;</code> method in the middle and just use the text you've accumulated so far.  You can use a <code>return</code> statement inside a Python block to do that.
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">%</span> <span class="k">if</span> <span class="ow">not</span> <span class="nb">len</span><span class="p">(</span><span class="n">records</span><span class="p">):</span>
    No records found.
    <span class="cp">&lt;%</span> <span class="k">return</span> <span class="cp">%&gt;</span>
<span class="cp">%</span><span class="k"> endif</span>
</pre></div>

    </div>
<p>Or perhaps:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="nb">len</span><span class="p">(</span><span class="n">records</span><span class="p">):</span>
        <span class="k">return</span>
<span class="cp">%&gt;</span>
</pre></div>

    </div>




    </div>




            <a href="#syntax">back to section top</a>
    </div>


</html>
    
    
    <A name="defs"></a>

    
    <div class="toolbar">
        <div class="prevnext">
            Previous: <a href="#syntax">Syntax</a>

            |
            Next: <a href="#runtime">The Mako Runtime Environment</a>
        </div>
        <h3><a href="documentation.html">Table of Contents</a></h3>
    </div>


    








    
    <A name="defs"></a>
    
    <div class="section">
    

    <h3>Defs</h3>
    
    

<p>The def is the single tag used to demarcate any block of text and/or code.  It exists within generated Python as a callable function. 
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;hello()&quot;</span><span class="cp">&gt;</span>
    hello world
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>They are normally called as expressions.
</p>

    
    

    <div class="code">
        <div class="highlight"><pre>the def:  <span class="cp">${</span><span class="n">hello</span><span class="p">()</span><span class="cp">}</span>
</pre></div>

    </div>
<p>If the <code>&lt;%def&gt;</code> is not nested inside of another <code>&lt;%def&gt;</code>, its known as a <strong>top level def</strong> and can be accessed anywhere in the template, including above where it was defined.
</p>
<p>All defs, top level or not, have access to the current contextual namespace in exactly the same way their containing template does.  Suppose the template below is executed with the variables <code>username</code> and <code>accountdata</code> inside the context:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre>Hello there <span class="cp">${</span><span class="n">username</span><span class="cp">}</span>, how are ya.  Lets see what your account says:

<span class="cp">${</span><span class="n">account</span><span class="p">()</span><span class="cp">}</span>

<span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;account()&quot;</span><span class="cp">&gt;</span>
    Account for <span class="cp">${</span><span class="n">username</span><span class="cp">}</span>:<span class="nt">&lt;br/&gt;</span>

    <span class="cp">%</span> <span class="k">for</span> <span class="n">row</span> <span class="ow">in</span> <span class="n">accountdata</span><span class="p">:</span>
        Value: <span class="cp">${</span><span class="n">row</span><span class="cp">}</span><span class="nt">&lt;br/&gt;</span>
    <span class="cp">%</span><span class="k"> endfor</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>The <code>username</code> and <code>accountdata</code> variables are present within the main template body as well as the body of the <code>account()</code> def.
</p>
<p>Since defs are just Python functions, you can define and pass arguments to them as well:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="n">account</span><span class="p">(</span><span class="n">accountname</span><span class="o">=</span><span class="s">&#39;john&#39;</span><span class="p">)</span><span class="cp">}</span>

<span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;account(accountname, type=&#39;regular&#39;)&quot;</span><span class="cp">&gt;</span>
    account name: <span class="cp">${</span><span class="n">accountname</span><span class="cp">}</span>, type <span class="cp">${</span><span class="nb">type</span><span class="cp">}</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>When you declare an argument signature for your def, they are required following normal Python conventions (i.e., all arguments are required except keyword arguments with a default value).  This is in contrast to using context-level variables, which evaluate to <code>UNDEFINED</code> if you reference a name that does not exist.
</p>


    
    <A name="defs_remotedefs"></a>
    
    <div class="subsection">
    

    <h3>Calling defs from Other Files</h3>
    
    

<p>Top level <code>&lt;%defs&gt;</code> are <strong>exported</strong> by your template's module, and can be called from the outside; including from other templates, as well as normal Python code.  Calling a <code>&lt;%def&gt;</code> from another template is something like using an <code>&lt;%include&gt;</code> - except you are calling a specific function within the template, not the whole template.
</p>
<p>The remote <code>&lt;%def&gt;</code> call is also a little bit like calling functions from other modules in Python.  There is an "import" step to pull the names from another template into your own template; then the function or functions are available.
</p>
<p>To import another template, use the <code>&lt;%namespace&gt;</code> tag:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">namespace</span> <span class="na">name=</span><span class="s">&quot;mystuff&quot;</span> <span class="na">file=</span><span class="s">&quot;mystuff.html&quot;</span><span class="cp">/&gt;</span>
</pre></div>

    </div>
<p>The above tag adds a local variable "mystuff" to the current scope.
</p>
<p>Then, just call the defs off of <code>mystuff</code>:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="n">mystuff</span><span class="o">.</span><span class="n">somedef</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mf">5</span><span class="p">,</span><span class="n">y</span><span class="o">=</span><span class="mf">7</span><span class="p">)</span><span class="cp">}</span>
</pre></div>

    </div>
<p>The <code>&lt;%namespace&gt;</code> tag also supports some of the other semantics of Python's <code>import</code> statement, including pulling names into the local variable space, or using <code>*</code> to represent all names, using the <code>import</code> attribute:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">namespace</span> <span class="na">file=</span><span class="s">&quot;mystuff.html&quot;</span> <span class="na">import=</span><span class="s">&quot;foo, bar&quot;</span><span class="cp">/&gt;</span>
</pre></div>

    </div>
<p>This is just a quick intro to the concept of a <strong>namespace</strong>, which is a central Mako concept that has its own chapter in these docs.  For more detail and examples, see <a href="#namespaces">Namespaces</a>.
</p>



            <a href="#defs">back to section top</a>
    </div>



    
    <A name="defs_programmatic"></a>
    
    <div class="subsection">
    

    <h3>Calling defs programmatically</h3>
    
    

<p>You can call def's programmatically from any <code>Template</code> object using the <code>get_def()</code> method, which returns a <code>DefTemplate</code> object.  This is a <code>Template</code> subclass which the parent <code>Template</code> creates, and is usable like any other template:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="kn">from</span> <span class="nn">mako.template</span> <span class="kn">import</span> <span class="n">Template</span>

<span class="n">template</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s">&quot;&quot;&quot;</span>
<span class="s">    &lt;</span><span class="si">%d</span><span class="s">ef name=&quot;hi(name)&quot;&gt;</span>
<span class="s">        hi ${name}!</span>
<span class="s">    &lt;/</span><span class="si">%d</span><span class="s">ef&gt;</span>

<span class="s">    &lt;</span><span class="si">%d</span><span class="s">ef name=&quot;bye(name)&quot;&gt;</span>
<span class="s">        bye ${name}!</span>
<span class="s">    &lt;/</span><span class="si">%d</span><span class="s">ef&gt;</span>
<span class="s">&quot;&quot;&quot;</span><span class="p">)</span>

<span class="k">print</span> <span class="n">template</span><span class="o">.</span><span class="n">get_def</span><span class="p">(</span><span class="s">&quot;hi&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;ed&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="n">template</span><span class="o">.</span><span class="n">get_def</span><span class="p">(</span><span class="s">&quot;bye&quot;</span><span class="p">)</span><span class="o">.</span><span class="n">render</span><span class="p">(</span><span class="n">name</span><span class="o">=</span><span class="s">&quot;ed&quot;</span><span class="p">)</span>
</pre></div>

    </div>



            <a href="#defs">back to section top</a>
    </div>



    
    <A name="defs_nesteddefs"></a>
    
    <div class="subsection">
    

    <h3>Defs within Defs</h3>
    
    

<p>The def model follows regular Python rules for closures.  Declaring <code>&lt;%def&gt;</code> inside another <code>&lt;%def&gt;</code> declares it within the parent's <strong>enclosing scope</strong>:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;mydef()&quot;</span><span class="cp">&gt;</span>
    <span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;subdef()&quot;</span><span class="cp">&gt;</span>
        a sub def
    <span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>

    im the def, and the subcomopnent is <span class="cp">${</span><span class="n">subdef</span><span class="p">()</span><span class="cp">}</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>Just like Python, names that exist outside the inner <code>&lt;%def&gt;</code> exist inside it as well:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span>
    <span class="n">x</span> <span class="o">=</span> <span class="mf">12</span>
<span class="cp">%&gt;</span>
<span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;outer()&quot;</span><span class="cp">&gt;</span>
    <span class="cp">&lt;%</span>
        <span class="n">y</span> <span class="o">=</span> <span class="mf">15</span>
    <span class="cp">%&gt;</span>
    <span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;inner()&quot;</span><span class="cp">&gt;</span>
        inner, x is <span class="cp">${</span><span class="n">x</span><span class="cp">}</span>, y is <span class="cp">${</span><span class="n">y</span><span class="cp">}</span>
    <span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>

    outer, x is <span class="cp">${</span><span class="n">x</span><span class="cp">}</span>, y is <span class="cp">${</span><span class="n">y</span><span class="cp">}</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>Assigning to a name inside of a def declares that name as local to the scope of that def (again, like Python itself).  This means the following code will raise an error:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span>
    <span class="n">x</span> <span class="o">=</span> <span class="mf">10</span>
<span class="cp">%&gt;</span>
<span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;somedef()&quot;</span><span class="cp">&gt;</span>
    <span class="cp">## error !</span>
    somedef, x is <span class="cp">${</span><span class="n">x</span><span class="cp">}</span>  
    <span class="cp">&lt;%</span>
        <span class="n">x</span> <span class="o">=</span> <span class="mf">27</span>  
    <span class="cp">%&gt;</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>...because the assignment to <code>x</code> declares x as local to the scope of <code>somedef</code>, rendering the "outer" version unreachable in the expression that tries to render it.
</p>



            <a href="#defs">back to section top</a>
    </div>



    
    <A name="defs_defswithcontent"></a>
    
    <div class="subsection">
    

    <h3>Calling a def with embedded content and/or other defs</h3>
    
    

<p>A flip-side to def within def is a def call with content.  This is where you call a def, and at the same time declare a block of content (or multiple blocks) that can be used by the def being called.  The main point of such a call is to create custom, nestable tags, just like any other template language's custom-tag creation system - where the external tag controls the execution of the nested tags and can communicate state to them.  Only with Mako, you don't have to use any external Python modules, you can define arbitrarily nestable tags right in your templates.
</p>
<p>To achieve this, the target def is invoked using the form <code>&lt;%namepacename:defname&gt;</code> instead of the normal <code>${}</code> syntax.  This syntax, introduced in Mako 0.2.3, is functionally equivalent another tag known as <code>call</code>, which takes the form <code>&lt;%call expr='namespacename.defname(args)'&gt;</code>.  While <code>%call</code> is available in all versions of Mako, the newer style is probably more familiar looking.  The <code>namespace</code> portion of the call is the name of the <strong>namespace</strong> in which the def is defined - in the most simple cases, this can be <code>local</code> or <code>self</code> to reference the current template's namespace (the difference between <code>local</code> and <code>self</code> is one of inheritance - see <a href="#namespaces_builtin">Built-in Namespaces</a> for details).
</p>
<p>When the target def is invoked, a variable <code>caller</code> is placed in its context which contains another namespace containing the body and other defs defined by the caller.  The body itself is referenced by the method <code>body()</code>.  Below, we build a <code>%def</code> that operates upon <code>caller.body()</code> to invoke the body of the custom tag:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;buildtable()&quot;</span><span class="cp">&gt;</span>
    <span class="nt">&lt;table&gt;</span>
        <span class="nt">&lt;tr&gt;&lt;td&gt;</span>
            <span class="cp">${</span><span class="n">caller</span><span class="o">.</span><span class="n">body</span><span class="p">()</span><span class="cp">}</span>
        <span class="nt">&lt;/td&gt;&lt;/tr&gt;</span>
    <span class="nt">&lt;/table&gt;</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>

<span class="cp">&lt;%</span><span class="nb">self:buildtable</span><span class="cp">&gt;</span>
    I am the table body.
<span class="cp">&lt;/%</span><span class="nb">self:buildtable</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>This produces the output (whitespace formatted):
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="nt">&lt;table&gt;</span>
    <span class="nt">&lt;tr&gt;&lt;td&gt;</span>
        I am the table body.
    <span class="nt">&lt;/td&gt;&lt;/tr&gt;</span>
<span class="nt">&lt;/table&gt;</span>
</pre></div>

    </div>
<p>Using the older <code>%call</code> syntax looks like:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;buildtable()&quot;</span><span class="cp">&gt;</span>
    <span class="nt">&lt;table&gt;</span>
        <span class="nt">&lt;tr&gt;&lt;td&gt;</span>
            <span class="cp">${</span><span class="n">caller</span><span class="o">.</span><span class="n">body</span><span class="p">()</span><span class="cp">}</span>
        <span class="nt">&lt;/td&gt;&lt;/tr&gt;</span>
    <span class="nt">&lt;/table&gt;</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>

<span class="cp">&lt;%</span><span class="nb">call</span> <span class="na">expr=</span><span class="s">&quot;buildtable()&quot;</span><span class="cp">&gt;</span>
    I am the table body.
<span class="cp">&lt;/%</span><span class="nb">call</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>The <code>body()</code> can be executed multiple times or not at all.  This means you can use def-call-with-content to build iterators, conditionals, etc:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;lister(count)&quot;</span><span class="cp">&gt;</span>
    <span class="cp">%</span> <span class="k">for</span> <span class="n">x</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mf">1</span><span class="p">,</span><span class="n">count</span><span class="p">):</span>
        <span class="cp">${</span><span class="n">caller</span><span class="o">.</span><span class="n">body</span><span class="p">()</span><span class="cp">}</span>
    <span class="cp">%</span><span class="k"> endfor</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>

<span class="cp">&lt;%</span><span class="nb">self:lister</span> <span class="na">count=</span><span class="s">&quot;${3}&quot;</span><span class="cp">&gt;</span>
    hi
<span class="cp">&lt;/%</span><span class="nb">self:lister</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>Produces:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre>hi
hi
hi
</pre></div>

    </div>
<p>Notice above we pass <code>3</code> as a Python expression, so that it remains as an integer.
</p>
<p>A custom "conditional" tag:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;conditional(expression)&quot;</span><span class="cp">&gt;</span>
    <span class="cp">%</span> <span class="k">if</span> <span class="n">expression</span><span class="p">:</span>
        <span class="cp">${</span><span class="n">caller</span><span class="o">.</span><span class="n">body</span><span class="p">()</span><span class="cp">}</span>
    <span class="cp">%</span><span class="k"> endif</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>

<span class="cp">&lt;%</span><span class="nb">self:conditional</span> <span class="na">expression=</span><span class="s">&quot;${4==4}&quot;</span><span class="cp">&gt;</span>
    im the result
<span class="cp">&lt;/%</span><span class="nb">self:conditional</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>Produces:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre>im the result
</pre></div>

    </div>
<p>But that's not all.  The <code>body()</code> function also can handle arguments, which will augment the local namespace of the body callable.  The caller must define the arguments which it expects to receive from its target def using the <code>args</code> attribute, which is a comma-separated list of argument names.  Below, our <code>&lt;%def&gt;</code> calls the <code>body()</code> of its caller, passing in an element of data from its argument:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;layoutdata(somedata)&quot;</span><span class="cp">&gt;</span>
    <span class="nt">&lt;table&gt;</span>
    <span class="cp">%</span> <span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">somedata</span><span class="p">:</span>
        <span class="nt">&lt;tr&gt;</span>
        <span class="cp">%</span> <span class="k">for</span> <span class="n">col</span> <span class="ow">in</span> <span class="n">item</span><span class="p">:</span>
            <span class="nt">&lt;td&gt;</span><span class="cp">${</span><span class="n">caller</span><span class="o">.</span><span class="n">body</span><span class="p">(</span><span class="n">col</span><span class="o">=</span><span class="n">col</span><span class="p">)</span><span class="cp">}</span><span class="nt">&lt;/td&gt;</span>
        <span class="cp">%</span><span class="k"> endfor</span>
        <span class="nt">&lt;/tr&gt;</span>
    <span class="cp">%</span><span class="k"> endfor</span>
    <span class="nt">&lt;/table&gt;</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>

<span class="cp">&lt;%</span><span class="nb">self:layoutdata</span> <span class="na">somedata=</span><span class="s">&quot;${[[1,2,3],[4,5,6],[7,8,9]]}&quot;</span> <span class="na">args=</span><span class="s">&quot;col&quot;</span><span class="cp">&gt;</span>\
Body data: <span class="cp">${</span><span class="n">col</span><span class="cp">}</span>\
<span class="cp">&lt;/%</span><span class="nb">self:layoutdata</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>Produces:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="nt">&lt;table&gt;</span>
   <span class="nt">&lt;tr&gt;</span>
       <span class="nt">&lt;td&gt;</span>Body data: 1<span class="nt">&lt;/td&gt;</span>
       <span class="nt">&lt;td&gt;</span>Body data: 2<span class="nt">&lt;/td&gt;</span>
       <span class="nt">&lt;td&gt;</span>Body data: 3<span class="nt">&lt;/td&gt;</span>
   <span class="nt">&lt;/tr&gt;</span>
   <span class="nt">&lt;tr&gt;</span>
       <span class="nt">&lt;td&gt;</span>Body data: 4<span class="nt">&lt;/td&gt;</span>
       <span class="nt">&lt;td&gt;</span>Body data: 5<span class="nt">&lt;/td&gt;</span>
       <span class="nt">&lt;td&gt;</span>Body data: 6<span class="nt">&lt;/td&gt;</span>
   <span class="nt">&lt;/tr&gt;</span>
   <span class="nt">&lt;tr&gt;</span>
       <span class="nt">&lt;td&gt;</span>Body data: 7<span class="nt">&lt;/td&gt;</span>
       <span class="nt">&lt;td&gt;</span>Body data: 8<span class="nt">&lt;/td&gt;</span>
       <span class="nt">&lt;td&gt;</span>Body data: 9<span class="nt">&lt;/td&gt;</span>
   <span class="nt">&lt;/tr&gt;</span>
<span class="nt">&lt;/table&gt;</span>
</pre></div>

    </div>
<p>You don't have to stick to calling just the <code>body()</code> function.  The caller can define any number of callables, allowing the <code>&lt;%call&gt;</code> tag to produce whole layouts:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;layout()&quot;</span><span class="cp">&gt;</span>
    <span class="cp">## a layout def</span>
    <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;mainlayout&quot;</span><span class="nt">&gt;</span>
        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;header&quot;</span><span class="nt">&gt;</span>
            <span class="cp">${</span><span class="n">caller</span><span class="o">.</span><span class="n">header</span><span class="p">()</span><span class="cp">}</span>
        <span class="nt">&lt;/div&gt;</span>
        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;sidebar&quot;</span><span class="nt">&gt;</span>
            <span class="cp">${</span><span class="n">caller</span><span class="o">.</span><span class="n">sidebar</span><span class="p">()</span><span class="cp">}</span>
        <span class="nt">&lt;/div&gt;</span>
        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;content&quot;</span><span class="nt">&gt;</span>
            <span class="cp">${</span><span class="n">caller</span><span class="o">.</span><span class="n">body</span><span class="p">()</span><span class="cp">}</span>
        <span class="nt">&lt;/div&gt;</span>
    <span class="nt">&lt;/div&gt;</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>

<span class="cp">## calls the layout def</span>
<span class="cp">&lt;%</span><span class="nb">self:layout</span><span class="cp">&gt;</span>
    <span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;header()&quot;</span><span class="cp">&gt;</span>
        I am the header
    <span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
    <span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;sidebar()&quot;</span><span class="cp">&gt;</span>
        <span class="nt">&lt;ul&gt;</span>
            <span class="nt">&lt;li&gt;</span>sidebar 1<span class="nt">&lt;/li&gt;</span>
            <span class="nt">&lt;li&gt;</span>sidebar 2<span class="nt">&lt;/li&gt;</span>
        <span class="nt">&lt;/ul&gt;</span>
    <span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>

        this is the body
<span class="cp">&lt;/%</span><span class="nb">self:layout</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>The above layout would produce:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;mainlayout&quot;</span><span class="nt">&gt;</span>
   <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;header&quot;</span><span class="nt">&gt;</span>
   I am the header
   <span class="nt">&lt;/div&gt;</span>

   <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;sidebar&quot;</span><span class="nt">&gt;</span>
   <span class="nt">&lt;ul&gt;</span>
       <span class="nt">&lt;li&gt;</span>sidebar 1<span class="nt">&lt;/li&gt;</span>
       <span class="nt">&lt;li&gt;</span>sidebar 2<span class="nt">&lt;/li&gt;</span>
   <span class="nt">&lt;/ul&gt;</span>
   <span class="nt">&lt;/div&gt;</span>

   <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;content&quot;</span><span class="nt">&gt;</span>
   this is the body
   <span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;/div&gt;</span>
</pre></div>

    </div>
<p>The number of things you can do with <code>&lt;%call&gt;</code> and/or the <code>&lt;%namespacename:defname&gt;</code> calling syntax is enormous.  You can create form widget libraries, such as an enclosing <code>&lt;FORM&gt;</code> tag and nested HTML input elements, or portable wrapping schemes using <code>&lt;div&gt;</code> or other elements.  You can create tags that interpret rows of data, such as from a database, providing the individual columns of each row to a <code>body()</code> callable which lays out the row any way it wants.  Basically anything you'd do with a "custom tag" or tag library in some other system, Mako provides via <code>&lt;%def&gt;</code>s and plain Python callables which are invoked via <code>&lt;%namespacename:defname&gt;</code> or <code>&lt;%call&gt;</code>.
</p>




    </div>




            <a href="#defs">back to section top</a>
    </div>


</html>
    
    
    <A name="runtime"></a>

    
    <div class="toolbar">
        <div class="prevnext">
            Previous: <a href="#defs">Defs</a>

            |
            Next: <a href="#namespaces">Namespaces</a>
        </div>
        <h3><a href="documentation.html">Table of Contents</a></h3>
    </div>


    








    
    <A name="runtime"></a>
    
    <div class="section">
    

    <h3>The Mako Runtime Environment</h3>
    
    

<p>This section describes a little bit about the objects and built-in functions that are available in templates.
</p>


    
    <A name="runtime_context"></a>
    
    <div class="subsection">
    

    <h3>Context</h3>
    
    

<p>The <code>Context</code> is the central object that is created when a template is first executed, and is responsible for handling all communication with the outside world.  This includes two major components, one of which is the output buffer, which is a file-like object such as Python's <code>StringIO</code> or similar, and the other a dictionary of variables that can be freely referenced within a template; this dictionary is a combination of the arguments sent to the <code>template.render()</code> function and some built-in variables provided by Mako's runtime environment.
</p>


    
    <A name="runtime_context_buffer"></a>
    
    <div class="subsection">
    

    <h3>The Buffer</h3>
    
    

<p>The buffer is stored within the <code>Context</code>, and writing to it is achieved by calling <code>context.write()</code>.  You usually don't need to care about this as all text within a template, as well as all expressions provided by <code>${}</code>, automatically send everything to this method.  The cases you might want to be aware of its existence are if you are dealing with various filtering/buffering scenarios, which are described in <a href="#filtering">Filtering and Buffering</a>, or if you want to programmatically send content to the output stream, such as within a <code>&lt;% %&gt;</code> block.
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span>
    <span class="n">context</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s">&quot;some programmatic text&quot;</span><span class="p">)</span>
<span class="cp">%&gt;</span>
</pre></div>

    </div>
<p>The actual buffer may or may not be the original buffer sent to the <code>Context</code> object, as various filtering/caching scenarios may "push" a new buffer onto the context's underlying buffer stack.  For this reason, just stick with <code>context.write()</code> and content will always go to the topmost buffer.
</p>



            <a href="#runtime">back to section top</a>
    </div>



    
    <A name="runtime_context_variables"></a>
    
    <div class="subsection">
    

    <h3>Context Variables</h3>
    
    

<p>When your template is compiled into a Python module, the body content is enclosed within a Python function called <code>render_body</code>.  Other top-level defs defined in the template are defined within their own function bodies which are named after the def's name with the prefix <code>render_</code> (i.e. <code>render_mydef</code>).  One of the first things that happens within these functions is that all variable names that are referenced within the function which are not defined in some other way (i.e. such as via assignment, module level imports, etc.) are pulled from the <code>Context</code> object's dictionary of variables.  This is how you're able to freely reference variable names in a template which automatically correspond to what was passed into the current <code>Context</code>.
</p>
<ul>
 <li><p><strong>What happens if I reference a variable name that is not in the current context?</strong> - the value you get back is a special value called <code>UNDEFINED</code>.  This is just a simple global variable with the class <code>mako.runtime.Undefined</code>.  The <code>UNDEFINED</code> object throws an error when you call <code>str()</code> on it, which is what happens if you try to use it in an expression.
</p>

 </li>

 <li><p><strong>Why not just return None?</strong>  Using <code>UNDEFINED</code> is more explicit and allows differentiation between a value of <code>None</code> that was explicitly passed to the <code>Context</code> and a value that wasn't present at all.
</p>

 </li>

 <li><p><strong>Why raise an exception when you call str() on it ?  Why not just return a blank string?</strong> - Mako tries to stick to the Python philosophy of "explicit is better than implicit".  In this case, its decided that the template author should be made to specifically handle a missing value rather than experiencing what may be a silent failure.  Since <code>UNDEFINED</code> is a singleton object just like Python's <code>True</code> or <code>False</code>, you can use the <code>is</code> operator to check for it:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">%</span> <span class="k">if</span> <span class="n">someval</span> <span class="ow">is</span> <span class="n">UNDEFINED</span><span class="p">:</span>
    someval is: no value
<span class="cp">%</span> <span class="k">else</span><span class="p">:</span>
    someval is: <span class="cp">${</span><span class="n">someval</span><span class="cp">}</span>
<span class="cp">%</span><span class="k"> endif</span>
</pre></div>

    </div>

 </li>
</ul>
<p>Another facet of the <code>Context</code> is that its dictionary of variables is <strong>immutable</strong>.  Whatever is set when <code>template.render()</code> is called is what stays.  Of course, since its Python, you can hack around this and change values in the context's internal dictionary, but this will probably will not work as well as you'd think.  The reason for this is that Mako in many cases creates copies of the <code>Context</code> object, which get sent to various elements of the template and inheriting templates used in an execution.  So changing the value in your local <code>Context</code> will not necessarily make that value available in other parts of the template's execution.  Examples of where Mako creates copies of the <code>Context</code> include within top-level def calls from the main body of the template (the context is used to propagate locally assigned variables into the scope of defs; since in the template's body they appear as inlined functions, Mako tries to make them act that way), and within an inheritance chain (each template in an inheritance chain has a different notion of <code>parent</code> and <code>next</code>, which are all stored in unique <code>Context</code> instances).
</p>
<ul>
 <li>
     <strong>So what if I want to set values that are global to everyone within a template request?</strong> - All you have to do is provide a dictionary to your <code>Context</code> when the template first runs, and everyone can just get/set variables from that.  Lets say its called <code>attributes</code>.
 </li>
</ul>
<p>Running the template looks like:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="n">output</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">attributes</span><span class="o">=</span><span class="p">{})</span>
</pre></div>

    </div>
<p>Within a template, just reference the dictionary:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span>
    <span class="n">attributes</span><span class="p">[</span><span class="s">&#39;foo&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;bar&#39;</span>
<span class="cp">%&gt;</span>
&#39;foo&#39; attribute is: <span class="cp">${</span><span class="n">attributes</span><span class="p">[</span><span class="s">&#39;foo&#39;</span><span class="p">]</span><span class="cp">}</span>
</pre></div>

    </div>
<ul>
 <li>
     <strong>Why can't "attributes" be a built-in feature of the Context?</strong> - This is an area where Mako is trying to make as few decisions about your application as it possibly can.  Perhaps you don't want your templates to use this technique of assigning and sharing data, or perhaps you have a different notion of the names and kinds of data structures that should be passed around.  Once again Mako would rather ask the user to be explicit.
 </li>
</ul>



            <a href="#runtime">back to section top</a>
    </div>



    
    <A name="runtime_context_accessors"></a>
    
    <div class="subsection">
    

    <h3>Context Methods and Accessors</h3>
    
    

<p>Significant members off of <code>Context</code> include:
</p>
<ul>
 <li><p><code>context[key]</code> / <code>context.get(key, default=None)</code> - dictionary-like accessors for the context.  Normally, any variable you use in your template is automatically pulled from the context if it isnt defined somewhere already.  Use the dictionary accessor and/or <code>get</code> method when you want a variable that <em>is</em> already defined somewhere else, such as in the local arguments sent to a %def call.  If a key is not present, like a dictionary it raises <code>KeyError</code>.
</p>

 </li>

 <li><p><code>keys()</code> - all the names defined within this context.
</p>

 </li>

 <li><p><code>kwargs</code> - this returns a <strong>copy</strong> of the context's dictionary of variables.  This is useful when you want to propagate the variables in the current context to a function as keyword arguments, i.e.:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="n">next</span><span class="o">.</span><span class="n">body</span><span class="p">(</span><span class="o">**</span><span class="n">context</span><span class="o">.</span><span class="n">kwargs</span><span class="p">)</span><span class="cp">}</span>
</pre></div>

    </div>

 </li>

 <li><p><code>write(text)</code> - write some text to the current output stream.
</p>

 </li>

 <li><p><code>lookup</code> - returns the <code>TemplateLookup</code> instance that is used for all file-lookups within the current execution (even though individual <code>Template</code> instances can conceivably have different instances of a <code>TemplateLookup</code>, only the <code>TemplateLookup</code> of the originally-called <code>Template</code> gets used in a particular execution).
</p>

 </li>
</ul>



    </div>




            <a href="#runtime">back to section top</a>
    </div>



    
    <A name="runtime_builtins"></a>
    
    <div class="subsection">
    

    <h3>All the built-in names</h3>
    
    

<p>A one-stop shop for all the names Mako defines.  Most of these names are instances of <code>Namespace</code>, which are described in the next section,   <a href="#namespaces">Namespaces</a>.  Also, most of these names other than <code>context</code> and <code>UNDEFINED</code> are also present <em>within</em> the <code>Context</code> itself.
</p>
<ul>
 <li>
     <code>local</code> - the namespace of the current template, described in <a href="#namespaces_builtin">Built-in Namespaces</a>
 </li>

 <li>
     <code>self</code> - the namespace of the topmost template in an inheritance chain (if any, otherwise the same as <code>local</code>), mostly described in <a href="#inheritance">Inheritance</a>
 </li>

 <li>
     <code>parent</code> - the namespace of the parent template in an inheritance chain (otherwise undefined); see <a href="#inheritance">Inheritance</a>
 </li>

 <li>
     <code>next</code> - the namespace of the next template in an inheritance chain (otherwise undefined); see <a href="#inheritance">Inheritance</a>
 </li>

 <li>
     <code>caller</code> - a "mini" namespace created when using the <code>&lt;%call&gt;</code> tag to define a "def call with content"; described in <a href="#defs_defswithcontent">Calling a def with embedded content and/or other defs</a>
 </li>

 <li>
     <code>capture</code> - a function that calls a given def and captures its resulting content into a string, which is returned.  Usage is described in <a href="#filtering_buffering">Buffering</a>
 </li>

 <li>
     <code>UNDEFINED</code> - a global singleton that is applied to all otherwise uninitialized template variables that were not located within the <code>Context</code> when rendering began.  Is an instance of <code>mako.runtime.Undefined</code>, and raises an exception when its <code>__str__()</code> method is called.
 </li>

 <li>
     <code>pageargs</code> - this is a dictionary which is present in a template which does not define any <em></em>kwargs section in its <code>&lt;%page&gt;</code> tag.  All keyword arguments sent to the <code>body()</code> function of a template (when used via namespaces) go here by default unless otherwise defined as a page argument.  If this makes no sense, it shouldn't; read the section <a href="#namespaces_body">The "body()" method</a>.
 </li>
</ul>




    </div>




            <a href="#runtime">back to section top</a>
    </div>


</html>
    
    
    <A name="namespaces"></a>

    
    <div class="toolbar">
        <div class="prevnext">
            Previous: <a href="#runtime">The Mako Runtime Environment</a>

            |
            Next: <a href="#inheritance">Inheritance</a>
        </div>
        <h3><a href="documentation.html">Table of Contents</a></h3>
    </div>


    








    
    <A name="namespaces"></a>
    
    <div class="section">
    

    <h3>Namespaces</h3>
    
    

<p>Namespaces are used to organize groups of components into categories, and also to "import" components from other files.
</p>
<p>If the file <code>components.html</code> defines these two components:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">## components.html</span>
<span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;comp1()&quot;</span><span class="cp">&gt;</span>
    this is comp1
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>

<span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;comp2(x)&quot;</span><span class="cp">&gt;</span>
    this is comp2, x is <span class="cp">${</span><span class="n">x</span><span class="cp">}</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>You can make another file, for example <code>index.html</code>, that pulls those two components into a namespace called <code>comp</code>:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">## index.html</span>
<span class="cp">&lt;%</span><span class="nb">namespace</span> <span class="na">name=</span><span class="s">&quot;comp&quot;</span> <span class="na">file=</span><span class="s">&quot;components.html&quot;</span><span class="cp">/&gt;</span>

Heres comp1:  <span class="cp">${</span><span class="n">comp</span><span class="o">.</span><span class="n">comp1</span><span class="p">()</span><span class="cp">}</span>
Heres comp2:  <span class="cp">${</span><span class="n">comp</span><span class="o">.</span><span class="n">comp2</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mf">5</span><span class="p">)</span><span class="cp">}</span>
</pre></div>

    </div>
<p>The <code>comp</code> variable above is an instance of <code>mako.runtime.Namespace</code>, a <strong>proxy object</strong> which delivers method calls to the underlying template callable using the current context.
</p>
<p><code>&lt;%namespace&gt;</code> also provides an <code>import</code> attribute which can be used to pull the names into the local namespace, removing the need to call it via the ".".  When <code>import</code> is used, the <code>name</code> attribute is optional.
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">namespace</span> <span class="na">file=</span><span class="s">&quot;components.html&quot;</span> <span class="na">import=</span><span class="s">&quot;comp1, comp2&quot;</span><span class="cp">/&gt;</span>

Heres comp1:  <span class="cp">${</span><span class="n">comp1</span><span class="p">()</span><span class="cp">}</span>
Heres comp2:  <span class="cp">${</span><span class="n">comp2</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mf">5</span><span class="p">)</span><span class="cp">}</span>
</pre></div>

    </div>
<p><code>import</code> also supports the "*" operator:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">namespace</span> <span class="na">file=</span><span class="s">&quot;components.html&quot;</span> <span class="na">import=</span><span class="s">&quot;*&quot;</span><span class="cp">/&gt;</span>

Heres comp1:  <span class="cp">${</span><span class="n">comp1</span><span class="p">()</span><span class="cp">}</span>
Heres comp2:  <span class="cp">${</span><span class="n">comp2</span><span class="p">(</span><span class="n">x</span><span class="o">=</span><span class="mf">5</span><span class="p">)</span><span class="cp">}</span>
</pre></div>

    </div>
<p>The names imported by the <code>import</code> attribute take precedence over any names that exist within the current context.
</p>
<p><strong>Note</strong> - in current versions of Mako, usage of "import='*'" is known to decrease performance of the template.  This will be fixed in a future release.
</p>


    
    <A name="namespaces_howtocall"></a>
    
    <div class="subsection">
    

    <h3>Ways to Call Namespaces</h3>
    
    

<p>There are essentially four ways to call a function from a namespace.
</p>
<p>The "expression" format, as described previously.  Namespaces are just Python objects with functions on them, and can
   be used in expressions like any other function:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="n">mynamespace</span><span class="o">.</span><span class="n">somefunction</span><span class="p">(</span><span class="s">&#39;some arg1&#39;</span><span class="p">,</span> <span class="s">&#39;some arg2&#39;</span><span class="p">,</span> <span class="n">arg3</span><span class="o">=</span><span class="s">&#39;some arg3&#39;</span><span class="p">,</span> <span class="n">arg4</span><span class="o">=</span><span class="s">&#39;some arg4&#39;</span><span class="p">)</span><span class="cp">}</span>
</pre></div>

    </div>
<p>Synonymous with the "expression" format is the "custom tag" format, when a "closed" tag is used.  This format, introduced in Mako 0.2.3, allows the usage of a "custom" Mako tag, with the function arguments passed in using named attributes:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">mynamespace:somefunction</span> <span class="na">arg1=</span><span class="s">&quot;some arg1&quot;</span> <span class="na">arg2=</span><span class="s">&quot;some arg2&quot;</span> <span class="na">arg3=</span><span class="s">&quot;some arg3&quot;</span> <span class="na">arg4=</span><span class="s">&quot;some arg4&quot;</span><span class="cp">/&gt;</span>
</pre></div>

    </div>
<p>When using tags, the values of the arguments are taken as literal strings by default.  To embed Python expressions as arguments, use the embedded expression format:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">mynamespace:somefunction</span> <span class="na">arg1=</span><span class="s">&quot;${someobject.format()}&quot;</span> <span class="na">arg2=</span><span class="s">&quot;${somedef(5, 12)}&quot;</span><span class="cp">/&gt;</span>
</pre></div>

    </div>
<p>The "custom tag" format is intended mainly for namespace functions which recognize body content, which in Mako is known as a "def with embedded content":
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">mynamespace:somefunction</span> <span class="na">arg1=</span><span class="s">&quot;some argument&quot;</span> <span class="na">args=</span><span class="s">&quot;x, y&quot;</span><span class="cp">&gt;</span>
    Some record: <span class="cp">${</span><span class="n">x</span><span class="cp">}</span>, <span class="cp">${</span><span class="n">y</span><span class="cp">}</span>
<span class="cp">&lt;/%</span><span class="nb">mynamespace:somefunction</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>The "classic" way to call defs with embedded content is the <code>&lt;%call&gt;</code> tag:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">call</span> <span class="na">expr=</span><span class="s">&quot;mynamespace.somefunction(arg1=&#39;some argument&#39;)&quot;</span> <span class="na">args=</span><span class="s">&quot;x, y&quot;</span><span class="cp">&gt;</span>
    Some record: <span class="cp">${</span><span class="n">x</span><span class="cp">}</span>, <span class="cp">${</span><span class="n">y</span><span class="cp">}</span>
<span class="cp">&lt;/%</span><span class="nb">call</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>For information on how to construct defs that embed content from the caller, see <a href="#defs_defswithcontent">Calling a def with embedded content and/or other defs</a>.
</p>



            <a href="#namespaces">back to section top</a>
    </div>



    
    <A name="namespaces_frommodules"></a>
    
    <div class="subsection">
    

    <h3>Namespaces from Regular Python Modules</h3>
    
    

<p>Namespaces can also import regular Python functions from modules.  These callables need to take at least one argument, <code>context</code>:
</p>
<p>A module file <code>some/module.py</code> might contain the callable:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre>def my_tag(context):
    context.write(&quot;hello world&quot;)
</pre></div>

    </div>
<p>A template can use this module via:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">namespace</span> <span class="na">name=</span><span class="s">&quot;hw&quot;</span> <span class="na">module=</span><span class="s">&quot;some.module&quot;</span><span class="cp">/&gt;</span>

<span class="cp">${</span><span class="n">hw</span><span class="o">.</span><span class="n">my_tag</span><span class="p">()</span><span class="cp">}</span>
</pre></div>

    </div>
<p>Note that the <code>context</code> argument is not needed in the call; the <code>namespace</code> tag creates a locally-scoped callable which takes care of it.
</p>



            <a href="#namespaces">back to section top</a>
    </div>



    
    <A name="namespaces_declaring"></a>
    
    <div class="subsection">
    

    <h3>Declaring defs in namespaces.</h3>
    
    

<p>The <code>&lt;%namespace&gt;</code> tag supports the definition of <code>&lt;%defs&gt;</code> directly inside the tag.  These defs become part of the namespace like any other function, and will override the definitions pulled in from a remote template or module:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">## define a namespace</span>
<span class="cp">&lt;%</span><span class="nb">namespace</span> <span class="na">name=</span><span class="s">&quot;stuff&quot;</span><span class="cp">&gt;</span>
    <span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;comp1()&quot;</span><span class="cp">&gt;</span>
        comp1
    <span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
<span class="cp">&lt;/%</span><span class="nb">namespace</span><span class="cp">&gt;</span>

<span class="cp">## then call it</span>
<span class="cp">${</span><span class="n">stuff</span><span class="o">.</span><span class="n">comp1</span><span class="p">()</span><span class="cp">}</span>
</pre></div>

    </div>



            <a href="#namespaces">back to section top</a>
    </div>



    
    <A name="namespaces_body"></a>
    
    <div class="subsection">
    

    <h3>The "body()" method</h3>
    
    

<p>Every namespace that is generated from a template contains a method called <code>body()</code>.  This method corresponds to the main body of the template, and plays its most important roles when using inheritance relationships as well as def-calls-with-content.
</p>
<p>Since the <code>body()</code> method is available from a namespace just like all the other defs defined in a template, what happens if you send arguments to it ?  By default, the <code>body()</code> method accepts no positional arguments, and for usefulness in inheritance scenarios will by default dump all keyword arguments into a dictionary called <code>pageargs</code>.  But if you actually want to get at the keyword arguments, Mako recommends you define your own argument signature explicitly.  You do this via using the <code>&lt;%page&gt;</code> tag:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">page</span> <span class="na">args=</span><span class="s">&quot;x, y, someval=8, scope=&#39;foo&#39;, **kwargs&quot;</span><span class="cp">/&gt;</span>
</pre></div>

    </div>
<p>A template which defines the above signature requires that the variables <code>x</code> and <code>y</code> are defined, defines default values for <code>someval</code> and <code>scope</code>, and sets up <code>**kwargs</code> to receive all other keyword arguments.  If <code>**kwargs</code> or similar is not present, the argument <code>**pageargs</code> gets tacked on by Mako.  When the template is called as a top-level template (i.e. via <code>template.render()</code>) or via the <code>&lt;%include&gt;</code> tag, the values for these arguments will be pulled from the <code>Context</code>.  In all other cases, i.e. via calling the <code>body()</code> method, the arguments are taken as ordinary arguments from the method call.  So above, the body might be called as:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="bp">self</span><span class="o">.</span><span class="n">body</span><span class="p">(</span><span class="mf">5</span><span class="p">,</span> <span class="n">y</span><span class="o">=</span><span class="mf">10</span><span class="p">,</span> <span class="n">someval</span><span class="o">=</span><span class="mf">15</span><span class="p">,</span> <span class="n">delta</span><span class="o">=</span><span class="mf">7</span><span class="p">)</span><span class="cp">}</span>
</pre></div>

    </div>
<p>The <code>Context</code> object also supplies a <code>kwargs</code> accessor, for cases when youd like to pass along whatever is in the context to a <code>body()</code> callable:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="n">next</span><span class="o">.</span><span class="n">body</span><span class="p">(</span><span class="o">**</span><span class="n">context</span><span class="o">.</span><span class="n">kwargs</span><span class="p">)</span><span class="cp">}</span>
</pre></div>

    </div>
<p>The usefulness of calls like the above become more apparent when one works with inheriting templates.  For more information on this, as well as the meanings of the names <code>self</code> and <code>next</code>, see <a href="#inheritance">Inheritance</a>.
</p>



            <a href="#namespaces">back to section top</a>
    </div>



    
    <A name="namespaces_properties"></a>
    
    <div class="subsection">
    

    <h3>Namespace methods and properties</h3>
    
    

<p>The <code>Namespace</code> class includes helpful accessors and methods:
</p>
<ul>
 <li>
     <code>attr</code> - allows access module level attributes by name.  This accessor allows templates to supply "scalar" attributes which are particularly handy in inheritance relationships.  See the example in <a href="#inheritance">Inheritance</a>.
 </li>

 <li>
     <code>module</code> - the Python module referenced by this Namespace.  If the namespace references a <code>Template</code>, then this module is the equivalent of <code>template.module</code>, i.e. the generated module for the template.
 </li>

 <li>
     <code>filename</code> - the path of the filesystem file used for this Namespace's module or template.  If this is a pure module-based Namespace, this evaluates to <code>module.__file__</code>.  If a template-based namespace, it evaluates to the original template file location.
 </li>

 <li>
     <code>template</code> - the <code>Template</code> object referenced by this Namespace, if any.
 </li>

 <li>
     <code>uri</code> - the uri for this Namespace's template (i.e. whatever was sent to <code>lookup.get_template()</code>).  This is the equivalent of <code>template.uri</code>.
 </li>

 <li>
     <code>context</code> - the <code>Context</code> object for this namespace.  Namespaces are often created with copies of contexts that contain slightly different data, particularly in inheritance scenarios.  Using the <code>Context</code> off of a <code>Namespace</code> one can traverse an entire chain of templates that inherit from one-another.
 </li>

 <li>
     <code>get_namespace(uri)</code> - this method returns a <code>Namespace</code> at the given <code>uri</code>.  If the given uri is a relative uri (i.e. it does not contain ia leading slash <code>/</code>), the uri is adjusted to be relative to the uri <strong>of the namespace itself</strong>.  This method is therefore mostly useful off of the built-in <code>local</code> namespace, described in the next section.  In most cases, a template wouldn't need this function, and should instead use the <code>&lt;%namespace&gt;</code> tag to load namespaces.  However, since all <code>&lt;%namespace&gt;</code> tags are evaulated before the body of the template ever runs, this method can be used to locate namespaces using expressions that were generated within the body code of the template, or to conditionally use a particular namespace.
 </li>
</ul>



            <a href="#namespaces">back to section top</a>
    </div>



    
    <A name="namespaces_builtin"></a>
    
    <div class="subsection">
    

    <h3>Built-in Namespaces</h3>
    
    

<p>The namespace is so great that Mako gives your template one (or two) for free.  The names of these namespaces are <code>local</code> and <code>self</code>.  Other built-in namespaces include <code>parent</code> and <code>next</code>, which are optional and are described in <a href="#inheritance">Inheritance</a>.
</p>


    
    <A name="namespaces_builtin_local"></a>
    
    <div class="subsection">
    

    <h3>local</h3>
    
    

<p>The <code>local</code> namespace is basically the namespace for the currently executing template.  This means that all of the top level defs defined in your template, as well as your template's <code>body()</code> function, are also available off of the <code>local</code> namespace.
</p>
<p>The <code>local</code> namespace is also where properties like <code>uri</code>, <code>filename</code>, and <code>module</code> and the <code>get_namespace</code> method can be particularly useful.
</p>



            <a href="#namespaces">back to section top</a>
    </div>



    
    <A name="namespaces_builtin_self"></a>
    
    <div class="subsection">
    

    <h3>self</h3>
    
    

<p>The <code>self</code> namespace, in the case of a template that does not use inheritance, is synonomous with <code>local</code>.  If inheritance is used, then <code>self</code> references the topmost template in the inheritance chain, where it is most useful for providing the ultimate form of various "method" calls which may have been overridden at various points in an inheritance chain.  See <a href="#inheritance">Inheritance</a>.
</p>



    </div>




            <a href="#namespaces">back to section top</a>
    </div>



    
    <A name="namespaces_inheritable"></a>
    
    <div class="subsection">
    

    <h3>Inheritable Namespaces</h3>
    
    

<p>The <code>&lt;%namespace&gt;</code> tag includes an optional attribute <code>inheritable=&quot;True&quot;</code>, which will cause the namespace to be attached to the <code>self</code> namespace.  Since <code>self</code> is globally available throughout an inheritance chain (described in the next section), all the templates in an inheritance chain can get at the namespace imported in a super-template via <code>self</code>.
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">## base.html</span>
<span class="cp">&lt;%</span><span class="nb">namespace</span> <span class="na">name=</span><span class="s">&quot;foo&quot;</span> <span class="na">file=</span><span class="s">&quot;foo.html&quot;</span> <span class="na">inheritable=</span><span class="s">&quot;True&quot;</span><span class="cp">/&gt;</span>

<span class="cp">${</span><span class="n">next</span><span class="o">.</span><span class="n">body</span><span class="p">()</span><span class="cp">}</span>

<span class="cp">## somefile.html</span>
<span class="cp">&lt;%</span><span class="nb">inherit</span> <span class="na">file=</span><span class="s">&quot;base.html&quot;</span><span class="cp">/&gt;</span>

<span class="cp">${</span><span class="bp">self</span><span class="o">.</span><span class="n">foo</span><span class="o">.</span><span class="n">bar</span><span class="p">()</span><span class="cp">}</span>
</pre></div>

    </div>
<p>This allows a super-template to load a whole bunch of namespaces that its inheriting templates can get to, without them having to explicitly load those namespaces themselves.
</p>
<p>The <code>import=&quot;*&quot;</code> part of the <code>&lt;%namespace&gt;</code> tag doesn't yet interact with the <code>inheritable</code> flag, so currently you have to use the explicit namespace name off of <code>self</code>, followed by the desired function name.  But more on this in a future release.
</p>




    </div>




            <a href="#namespaces">back to section top</a>
    </div>


</html>
    
    
    <A name="inheritance"></a>

    
    <div class="toolbar">
        <div class="prevnext">
            Previous: <a href="#namespaces">Namespaces</a>

            |
            Next: <a href="#filtering">Filtering and Buffering</a>
        </div>
        <h3><a href="documentation.html">Table of Contents</a></h3>
    </div>


    








    
    <A name="inheritance"></a>
    
    <div class="section">
    

    <h3>Inheritance</h3>
    
    

<p>Using template inheritance, two or more templates can organize themselves into an <strong>inheritance chain</strong>, where content and functions from all involved templates can be intermixed.  The general paradigm of template inheritance is this:  if a template <code>A</code> inherits from template <code>B</code>, then template <code>A</code> agrees to send the executional control to template <code>B</code> at runtime (<code>A</code> is called the <strong>inheriting</strong> template).  Template <code>B</code>, the <strong>inherited</strong> template, then makes decisions as to what resources from <code>A</code> shall be executed.
</p>
<p>In practice, it looks like this.  Heres a hypothetical inheriting template, <code>index.html</code>:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">## index.html</span>
<span class="cp">&lt;%</span><span class="nb">inherit</span> <span class="na">file=</span><span class="s">&quot;base.html&quot;</span><span class="cp">/&gt;</span>

<span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;header()&quot;</span><span class="cp">&gt;</span>
    this is some header content
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>

this is the body content.
</pre></div>

    </div>
<p>And <code>base.html</code>, the inherited template:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">## base.html</span>
<span class="nt">&lt;html&gt;</span>
    <span class="nt">&lt;body&gt;</span>
        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;header&quot;</span><span class="nt">&gt;</span>
            <span class="cp">${</span><span class="bp">self</span><span class="o">.</span><span class="n">header</span><span class="p">()</span><span class="cp">}</span>
        <span class="nt">&lt;/div&gt;</span>

        <span class="cp">${</span><span class="bp">self</span><span class="o">.</span><span class="n">body</span><span class="p">()</span><span class="cp">}</span>

        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;footer&quot;</span><span class="nt">&gt;</span>
            <span class="cp">${</span><span class="bp">self</span><span class="o">.</span><span class="n">footer</span><span class="p">()</span><span class="cp">}</span>
        <span class="nt">&lt;/div&gt;</span>
    <span class="nt">&lt;/body&gt;</span>
<span class="nt">&lt;/html&gt;</span>

<span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;footer()&quot;</span><span class="cp">&gt;</span>
    this is the footer
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>Here is a breakdown of the execution:
</p>
<ul>
 <li><p>When <code>index.html</code> is rendered, control immediately passes to <code>base.html</code>.
</p>

 </li>

 <li><p><code>base.html</code> then renders the top part of an HTML document, then calls the method <code>header()</code> off of a built in namespace called <code>self</code> (this namespace was first introduced in the Namespaces chapter in <a href="#namespaces_builtin_self">self</a>).  Since <code>index.html</code> is the topmost template and also defines a def called <code>header()</code>, its this <code>header()</code> def that gets executed.
</p>

 </li>

 <li><p>Control comes back to <code>base.html</code>.  Some more HTML is rendered.
</p>

 </li>

 <li><p><code>base.html</code> executes <code>self.body()</code>.  The <code>body()</code> function on all template-based namespaces refers to the main body of the template, therefore the main body of <code>index.html</code> is rendered.
</p>

 </li>

 <li><p>Control comes back to <code>base.html</code>.  More HTML is rendered, then the <code>self.footer()</code> expression is invoked.
</p>

 </li>

 <li><p>The <code>footer</code> def is only defined in <code>base.html</code>, so being the topmost definition of <code>footer</code>, its the one that executes.  If <code>index.html</code> also specified <code>footer</code>, then its version would <strong>override</strong> that of the base.
</p>

 </li>

 <li><p><code>base.html</code> finishes up rendering its HTML and the template is complete, producing:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="nt">&lt;html&gt;</span>
    <span class="nt">&lt;body&gt;</span>
        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;header&quot;</span><span class="nt">&gt;</span>
            this is some header content
        <span class="nt">&lt;/div&gt;</span>

        this is the body content.

        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;footer&quot;</span><span class="nt">&gt;</span>
            this is the footer
        <span class="nt">&lt;/div&gt;</span>
    <span class="nt">&lt;/body&gt;</span>
<span class="nt">&lt;/html&gt;</span>
</pre></div>

    </div>

 </li>
</ul>
<p>...and that is template inheritance in a nutshell.  The main idea is that the methods that you call upon <code>self</code> always correspond to the topmost definition of that method.  Very much the way <code>self</code> works in a Python class, even though Mako is not actually using Python class inheritance to implement this functionality.  (Mako doesn't take the "inheritance" metaphor too seriously; while useful to setup some commonly recognized semantics, a textual template is not very much like an object-oriented class construct in practice).
</p>


    
    <A name="inheritance_next"></a>
    
    <div class="subsection">
    

    <h3>Using the "next" namespace to produce content wrapping</h3>
    
    

<p>Sometimes you have an inheritance chain that spans more than two templates.  Or maybe you don't, but youd like to build your system such that extra inherited templates can be inserted in the middle of a chain where they would be smoothly integrated.  If each template wants to define its layout just within its main body, you can't just call <code>self.body()</code> to get at the inheriting template's body, since that is only the topmost body.  To get at the body of the <em>next</em> template, you call upon the namespace <code>next</code>, which is the namespace of the template <strong>immediately following</strong> the current template.
</p>
<p>Lets change the line in <code>base.html</code> which calls upon <code>self.body()</code> to instead call upon <code>next.body()</code>:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">## base.html</span>
<span class="nt">&lt;html&gt;</span>
    <span class="nt">&lt;body&gt;</span>
        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;header&quot;</span><span class="nt">&gt;</span>
            <span class="cp">${</span><span class="bp">self</span><span class="o">.</span><span class="n">header</span><span class="p">()</span><span class="cp">}</span>
        <span class="nt">&lt;/div&gt;</span>

        <span class="cp">${</span><span class="n">next</span><span class="o">.</span><span class="n">body</span><span class="p">()</span><span class="cp">}</span>

        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;footer&quot;</span><span class="nt">&gt;</span>
            <span class="cp">${</span><span class="bp">self</span><span class="o">.</span><span class="n">footer</span><span class="p">()</span><span class="cp">}</span>
        <span class="nt">&lt;/div&gt;</span>
    <span class="nt">&lt;/body&gt;</span>
<span class="nt">&lt;/html&gt;</span>

<span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;footer()&quot;</span><span class="cp">&gt;</span>
    this is the footer
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>Lets also add an intermediate template called <code>layout.html</code>, which inherits from <code>base.html</code>:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">## layout.html</span>
<span class="cp">&lt;%</span><span class="nb">inherit</span> <span class="na">file=</span><span class="s">&quot;base.html&quot;</span><span class="cp">/&gt;</span>
<span class="nt">&lt;ul&gt;</span>
    <span class="cp">${</span><span class="bp">self</span><span class="o">.</span><span class="n">toolbar</span><span class="p">()</span><span class="cp">}</span>
<span class="nt">&lt;/ul&gt;</span>
<span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;mainlayout&quot;</span><span class="nt">&gt;</span>
    <span class="cp">${</span><span class="n">next</span><span class="o">.</span><span class="n">body</span><span class="p">()</span><span class="cp">}</span>
<span class="nt">&lt;/div&gt;</span>

<span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;toolbar()&quot;</span><span class="cp">&gt;</span>
    <span class="nt">&lt;li&gt;</span>selection 1<span class="nt">&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;</span>selection 2<span class="nt">&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;</span>selection 3<span class="nt">&lt;/li&gt;</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>And finally change <code>index.html</code> to inherit from <code>layout.html</code> instead:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">## index.html</span>
<span class="cp">&lt;%</span><span class="nb">inherit</span> <span class="na">file=</span><span class="s">&quot;layout.html&quot;</span><span class="cp">/&gt;</span>

<span class="cp">## .. rest of template</span>
</pre></div>

    </div>
<p>In this setup, each call to <code>next.body()</code> will render the body of the next template in the inheritance chain (which can be written as <code>base.html -&gt; layout.html -&gt; index.html</code>).  Control is still first passed to the bottommost template <code>base.html</code>, and <code>self</code> still references the topmost definition of any particular def.
</p>
<p>The output we get would be:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="nt">&lt;html&gt;</span>
    <span class="nt">&lt;body&gt;</span>
        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;header&quot;</span><span class="nt">&gt;</span>
            this is some header content
        <span class="nt">&lt;/div&gt;</span>

        <span class="nt">&lt;ul&gt;</span>
            <span class="nt">&lt;li&gt;</span>selection 1<span class="nt">&lt;/li&gt;</span>
            <span class="nt">&lt;li&gt;</span>selection 2<span class="nt">&lt;/li&gt;</span>
            <span class="nt">&lt;li&gt;</span>selection 3<span class="nt">&lt;/li&gt;</span>
        <span class="nt">&lt;/ul&gt;</span>

        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;mainlayout&quot;</span><span class="nt">&gt;</span>
        this is the body content.
        <span class="nt">&lt;/div&gt;</span>

        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;footer&quot;</span><span class="nt">&gt;</span>
            this is the footer
        <span class="nt">&lt;/div&gt;</span>
    <span class="nt">&lt;/body&gt;</span>
<span class="nt">&lt;/html&gt;</span>
</pre></div>

    </div>
<p>So above, we have the <code>&lt;html&gt;</code>, <code>&lt;body&gt;</code> and <code>header</code>/<code>footer</code> layout of <code>base.html</code>, we have the <code>&lt;ul&gt;</code> and <code>mainlayout</code> section of <code>layout.html</code>, and the main body of <code>index.html</code> as well as its overridden <code>header</code> def.  The <code>layout.html</code> template is inserted into the middle of the chain without <code>base.html</code> having to change anything.  Without the <code>next</code> namespace, only the main body of <code>index.html</code> could be used; there would be no way to call <code>layout.html</code>'s body content.
</p>



            <a href="#inheritance">back to section top</a>
    </div>



    
    <A name="inheritance_parent"></a>
    
    <div class="subsection">
    

    <h3>Using the "parent" namespace to augment defs</h3>
    
    

<p>Lets now look at the other inheritance-specific namespace, the opposite of <code>next</code> called <code>parent</code>.  <code>parent</code> is the namespace of the template <strong>immediately preceding</strong> the current template.  What is most useful about this namespace is the methods within it which can be accessed within overridden versions of those methods.  This is not as hard as it sounds and is very much like using the <code>super</code> keyword in Python.  Lets modify <code>index.html</code> to augment the list of selections provided by the <code>toolbar</code> function in <code>layout.html</code>:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">## index.html</span>
<span class="cp">&lt;%</span><span class="nb">inherit</span> <span class="na">file=</span><span class="s">&quot;layout.html&quot;</span><span class="cp">/&gt;</span>

<span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;header()&quot;</span><span class="cp">&gt;</span>
    this is some header content
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>

<span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;toolbar()&quot;</span><span class="cp">&gt;</span>
    <span class="cp">## call the parent&#39;s toolbar first</span>
    <span class="cp">${</span><span class="n">parent</span><span class="o">.</span><span class="n">toolbar</span><span class="p">()</span><span class="cp">}</span>
    <span class="nt">&lt;li&gt;</span>selection 4<span class="nt">&lt;/li&gt;</span>
    <span class="nt">&lt;li&gt;</span>selection 5<span class="nt">&lt;/li&gt;</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>

this is the body content.
</pre></div>

    </div>
<p>Above, we implemented a <code>toolbar()</code> function, which is meant to override the definition of <code>toolbar</code> within the inherited template <code>layout.html</code>.  However, since we want the content from that of <code>layout.html</code> as well, we call it via the <code>parent</code> namespace whenever we want it's content, in this case before we add our own selections.  So the output for the whole thing is now:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="nt">&lt;html&gt;</span>
    <span class="nt">&lt;body&gt;</span>
        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;header&quot;</span><span class="nt">&gt;</span>
            this is some header content
        <span class="nt">&lt;/div&gt;</span>

        <span class="nt">&lt;ul&gt;</span>
            <span class="nt">&lt;li&gt;</span>selection 1<span class="nt">&lt;/li&gt;</span>
            <span class="nt">&lt;li&gt;</span>selection 2<span class="nt">&lt;/li&gt;</span>
            <span class="nt">&lt;li&gt;</span>selection 3<span class="nt">&lt;/li&gt;</span>
            <span class="nt">&lt;li&gt;</span>selection 4<span class="nt">&lt;/li&gt;</span>
            <span class="nt">&lt;li&gt;</span>selection 5<span class="nt">&lt;/li&gt;</span>
        <span class="nt">&lt;/ul&gt;</span>

        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;mainlayout&quot;</span><span class="nt">&gt;</span>
        this is the body content.
        <span class="nt">&lt;/div&gt;</span>

        <span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;footer&quot;</span><span class="nt">&gt;</span>
            this is the footer
        <span class="nt">&lt;/div&gt;</span>
    <span class="nt">&lt;/body&gt;</span>
<span class="nt">&lt;/html&gt;</span>
</pre></div>

    </div>
<p>and you're now a template inheritance ninja !
</p>



            <a href="#inheritance">back to section top</a>
    </div>



    
    <A name="inheritance_inheritable"></a>
    
    <div class="subsection">
    

    <h3>Inheritable Attributes</h3>
    
    

<p>The <code>attr</code> accessor of the <code>Namespace</code> object allows access to module level variables declared in a template.  By accessing <code>self.attr</code>, you can access regular attributes from the inheritance chain as declared in <code>&lt;%! %&gt;</code> sections.  Such as:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%!</span>
    <span class="n">class_</span> <span class="o">=</span> <span class="s">&quot;grey&quot;</span>
<span class="cp">%&gt;</span>

<span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;</span><span class="cp">${</span><span class="bp">self</span><span class="o">.</span><span class="n">attr</span><span class="o">.</span><span class="n">class_</span><span class="cp">}</span><span class="s">&quot;</span><span class="nt">&gt;</span>
    <span class="cp">${</span><span class="bp">self</span><span class="o">.</span><span class="n">body</span><span class="p">()</span><span class="cp">}</span>
<span class="nt">&lt;/div&gt;</span>
</pre></div>

    </div>
<p>If a an inheriting template overrides <code>class_</code> to be <code>white</code>, as in:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%!</span>
    <span class="n">class_</span> <span class="o">=</span> <span class="s">&quot;white&quot;</span>
<span class="cp">%&gt;</span>
<span class="cp">&lt;%</span><span class="nb">inherit</span> <span class="na">file=</span><span class="s">&quot;parent.html&quot;</span><span class="cp">/&gt;</span>

This is the body
</pre></div>

    </div>
<p>You'll get output like:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">&quot;white&quot;</span><span class="nt">&gt;</span>
    This is the body
<span class="nt">&lt;/div&gt;</span>
</pre></div>

    </div>




    </div>




            <a href="#inheritance">back to section top</a>
    </div>


</html>
    
    
    <A name="filtering"></a>

    
    <div class="toolbar">
        <div class="prevnext">
            Previous: <a href="#inheritance">Inheritance</a>

            |
            Next: <a href="#unicode">The Unicode Chapter</a>
        </div>
        <h3><a href="documentation.html">Table of Contents</a></h3>
    </div>


    








    
    <A name="filtering"></a>
    
    <div class="section">
    

    <h3>Filtering and Buffering</h3>
    
    



    
    <A name="filtering_expression"></a>
    
    <div class="subsection">
    

    <h3>Expression Filtering</h3>
    
    

<p>As described in the Syntax chapter, the "<code>|</code>" operator can be applied to a "<code>${}</code>" expression to apply escape filters to the output:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="s">&quot;this is some text&quot;</span> <span class="o">|</span> <span class="n">u</span><span class="cp">}</span>
</pre></div>

    </div>
<p>The above expression applies URL escaping to the expression, and produces <code>this+is+some+text</code>.
</p>
<p>The built-in escape flags are:
</p>
<ul>
 <li>
     <code>u</code> : URL escaping, provided by <code>urllib.quote_plus(string.encode('utf-8'))</code>
 </li>

 <li>
     <code>h</code> : HTML escaping, provided by <code>cgi.escape(string, True)</code>
 </li>

 <li>
     <code>x</code> : XML escaping
 </li>

 <li>
     <code>trim</code> : whitespace trimming, provided by <code>string.strip()</code>
 </li>

 <li>
     <code>entity</code> : produces HTML entity references for applicable strings, derived from <code>htmlentitydefs</code>
 </li>

 <li>
     <code>unicode</code> : produces a Python unicode string (this function is applied by default).
 </li>

 <li>
     <code>decode.&lt;some encoding&gt;</code> : decode input into a Python unicode with the specified encoding
 </li>

 <li>
     <code>n</code> : disable all default filtering; only filters specified in the local expression tag will be applied.
 </li>
</ul>
<p>To apply more than one filter, separate them by a comma:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="s">&quot;  &lt;tag&gt;some value&lt;/tag&gt; &quot;</span> <span class="o">|</span> <span class="n">h</span><span class="p">,</span><span class="n">trim</span><span class="cp">}</span>
</pre></div>

    </div>
<p>The above produces <code>&amp;lt;tag&amp;gt;some value&amp;lt;/tag&amp;gt;</code>, with no leading or trailing whitespace.  The HTML escaping function is applied first, the "trim" function second.
</p>
<p>Naturally, you can make your own filters too.  A filter is just a Python function that accepts a single string argument, and returns the filtered result.  The expressions after the <code>|</code> operator draw upon the local namespace of the template in which they appear, meaning you can define escaping functions locally:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%!</span>
    <span class="k">def</span> <span class="nf">myescape</span><span class="p">(</span><span class="n">text</span><span class="p">):</span>
        <span class="k">return</span> <span class="s">&quot;&lt;TAG&gt;&quot;</span> <span class="o">+</span> <span class="n">text</span> <span class="o">+</span> <span class="s">&quot;&lt;/TAG&gt;&quot;</span>
<span class="cp">%&gt;</span>

Heres some tagged text: <span class="cp">${</span><span class="s">&quot;text&quot;</span> <span class="o">|</span> <span class="n">myescape</span><span class="cp">}</span>
</pre></div>

    </div>
<p>Or from any Python module:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%!</span>
    <span class="kn">import</span> <span class="nn">myfilters</span>
<span class="cp">%&gt;</span>

Heres some tagged text: <span class="cp">${</span><span class="s">&quot;text&quot;</span> <span class="o">|</span> <span class="n">myfilters</span><span class="o">.</span><span class="n">tagfilter</span><span class="cp">}</span>
</pre></div>

    </div>
<p>A page can apply a default set of filters to all expression tags using the <code>expression_filter</code> argument to the <code>%page</code> tag:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">page</span> <span class="na">expression_filter=</span><span class="s">&quot;h&quot;</span><span class="cp">/&gt;</span>

Escaped text:  <span class="cp">${</span><span class="s">&quot;&lt;html&gt;some html&lt;/html&gt;&quot;</span><span class="cp">}</span>
</pre></div>

    </div>
<p>Result:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre>Escaped text: <span class="ni">&amp;lt;</span>html<span class="ni">&amp;gt;</span>some html<span class="ni">&amp;lt;</span>/html<span class="ni">&amp;gt;</span>
</pre></div>

    </div>


    
    <A name="filtering_expression_defaultfilters"></a>
    
    <div class="subsection">
    

    <h3>The default_filters Argument</h3>
    
    

<p><strong>New in version 0.1.2</strong>
</p>
<p>In addition to the <code>expression_filter</code> argument, the <code>default_filters</code> argument to both <code>Template</code> and <code>TemplateLookup</code> can specify filtering for all expression tags at the programmatic level.  This array-based argument, when given its default argument of <code>None</code>, will be internally set to <code>[&quot;unicode&quot;]</code>, except when <code>disable_unicode=True</code> is set in which case it defaults to <code>[&quot;str&quot;]</code>:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="n">t</span> <span class="o">=</span> <span class="n">TemplateLookup</span><span class="p">(</span><span class="n">directories</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;/tmp&#39;</span><span class="p">],</span> <span class="n">default_filters</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;unicode&#39;</span><span class="p">])</span>
</pre></div>

    </div>
<p>To replace the usual <code>unicode</code> function with a specific encoding, the <code>decode</code> filter can be substituted:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="n">t</span> <span class="o">=</span> <span class="n">TemplateLookup</span><span class="p">(</span><span class="n">directories</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;/tmp&#39;</span><span class="p">],</span> <span class="n">default_filters</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;decode.utf8&#39;</span><span class="p">])</span>
</pre></div>

    </div>
<p>To disable <code>default_filters</code> entirely, set it to an empty list:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="n">t</span> <span class="o">=</span> <span class="n">TemplateLookup</span><span class="p">(</span><span class="n">directories</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;/tmp&#39;</span><span class="p">],</span> <span class="n">default_filters</span><span class="o">=</span><span class="p">[])</span>
</pre></div>

    </div>
<p>Any string name can be added to <code>default_filters</code> where it will be added to all expressions as a filter.  The filters are applied from left to right, meaning the leftmost filter is applied first.
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="n">templatetext</span><span class="p">,</span> <span class="n">default_filters</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;unicode&#39;</span><span class="p">,</span> <span class="s">&#39;myfilter&#39;</span><span class="p">])</span>
</pre></div>

    </div>
<p>To ease the usage of <code>default_filters</code> with custom filters, you can also add imports (or other code) to all templates using the <code>imports</code> argument:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="n">t</span> <span class="o">=</span> <span class="n">TemplateLookup</span><span class="p">(</span><span class="n">directories</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;/tmp&#39;</span><span class="p">],</span> 
    <span class="n">default_filters</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;unicode&#39;</span><span class="p">,</span> <span class="s">&#39;myfilter&#39;</span><span class="p">],</span> 
    <span class="n">imports</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;from mypackage import myfilter&#39;</span><span class="p">])</span>
</pre></div>

    </div>
<p>The above will generate templates something like this:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="c"># ....</span>
<span class="kn">from</span> <span class="nn">mypackage</span> <span class="kn">import</span> <span class="n">myfilter</span>

<span class="k">def</span> <span class="nf">render_body</span><span class="p">(</span><span class="n">context</span><span class="p">):</span>
    <span class="n">context</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">myfilter</span><span class="p">(</span><span class="nb">unicode</span><span class="p">(</span><span class="s">&quot;some text&quot;</span><span class="p">)))</span>
</pre></div>

    </div>



            <a href="#filtering">back to section top</a>
    </div>



    
    <A name="filtering_expression_turning"></a>
    
    <div class="subsection">
    

    <h3>Turning off Filtering with the "n" filter</h3>
    
    

<p>In all cases the special <code>n</code> filter, used locally within an expression, will <strong>disable</strong> all filters declared in the <code>&lt;%page&gt;</code> tag as well <code>default_filters</code>.  Such as:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="s">&#39;myexpression&#39;</span> <span class="o">|</span> <span class="n">n</span><span class="cp">}</span>
</pre></div>

    </div>
<p>Will render <code>myexpression</code> with no filtering of any kind, and
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="s">&#39;myexpression&#39;</span> <span class="o">|</span> <span class="n">n</span><span class="p">,</span> <span class="n">trim</span><span class="cp">}</span>
</pre></div>

    </div>
<p>will render <code>myexpression</code> using the <code>trim</code> filter only.  <br></br>
</p>



    </div>




            <a href="#filtering">back to section top</a>
    </div>



    
    <A name="filtering_filtering"></a>
    
    <div class="subsection">
    

    <h3>Filtering Defs</h3>
    
    

<p>The <code>%def</code> tag has a filter argument which will apply the given list of filter functions to the output of the <code>%def</code>:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;foo()&quot;</span> <span class="na">filter=</span><span class="s">&quot;h, trim&quot;</span><span class="cp">&gt;</span>
    <span class="nt">&lt;b&gt;</span>this is bold<span class="nt">&lt;/b&gt;</span>
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>When the filter attribute is applied to a def as above, the def is automatically <strong>buffered</strong> as well.  This is described next.
</p>



            <a href="#filtering">back to section top</a>
    </div>



    
    <A name="filtering_buffering"></a>
    
    <div class="subsection">
    

    <h3>Buffering</h3>
    
    

<p>One of Mako's central design goals is speed.  To this end, all of the textual content within a template and its various callables is by default piped directly to the single buffer that is stored within the <code>Context</code> object.  While this normally is easy to miss, it has certain side effects.  The main one is that when you call a def using the normal expression syntax, i.e. <code>${somedef()}</code>, it may appear that the return value of the function is the content it produced, which is then delivered to your template just like any other expression substitution, except that  normally, this is not the case; the return value of <code>${somedef()}</code> is simply the empty string <code>''</code>.  By the time you receive this empty string, the output of <code>somedef()</code> has been sent to the underlying buffer.
</p>
<p>You may not want this effect, if for example you are doing something like this:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="s">&quot; results &quot;</span> <span class="o">+</span> <span class="n">somedef</span><span class="p">()</span> <span class="o">+</span> <span class="s">&quot; more results &quot;</span><span class="cp">}</span>
</pre></div>

    </div>
<p>If the <code>somedef()</code> function produced the content "<code>somedef's results</code>", the above template would produce this output:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre>somedef&#39;s results results more results
</pre></div>

    </div>
<p>This is because <code>somedef()</code> fully executes before the expression returns the results of its concatenation; the concatenation in turn receives just the empty string as its middle expression.
</p>
<p>Mako provides two ways to work around this.  One is by applying buffering to the <code>%def</code> itself:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;somedef()&quot;</span> <span class="na">buffered=</span><span class="s">&quot;True&quot;</span><span class="cp">&gt;</span>
    somedef&#39;s results
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
</pre></div>

    </div>
<p>The above definition will generate code similar to this:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre>def somedef():
    context.push_buffer()
    try:
        context.write(&quot;somedef&#39;s results&quot;)
    finally:
        buf = context.pop_buffer()
    return buf.getvalue()
</pre></div>

    </div>
<p>So that the content of <code>somedef()</code> is sent to a second buffer, which is then popped off the stack and its value returned.  The speed hit inherent in buffering the output of a def is also apparent.
</p>
<p>Note that the <code>filter</code> argument on %def also causes the def to be buffered.  This is so that the final content of the %def can be delivered to the escaping function in one batch, which reduces method calls and also produces more deterministic behavior for the filtering function itself, which can possibly be useful for a filtering function that wishes to apply a transformation to the text as a whole.
</p>
<p>The other way to buffer the output of a def or any Mako callable is by using the built-in <code>capture</code> function.  This function performs an operation similar to the above buffering operation except it is specified by the caller.
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="s">&quot; results &quot;</span> <span class="o">+</span> <span class="n">capture</span><span class="p">(</span><span class="n">somedef</span><span class="p">)</span> <span class="o">+</span> <span class="s">&quot; more results &quot;</span><span class="cp">}</span>
</pre></div>

    </div>
<p>Note that the first argument to the <code>capture</code> function is <strong>the function itself</strong>, not the result of calling it.  This is because the <code>capture</code> function takes over the job of actually calling the target function, after setting up a buffered environment.  To send arguments to the function, just send them to <code>capture</code> instead:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="n">capture</span><span class="p">(</span><span class="n">somedef</span><span class="p">,</span> <span class="mf">17</span><span class="p">,</span> <span class="s">&#39;hi&#39;</span><span class="p">,</span> <span class="n">use_paging</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span><span class="cp">}</span>
</pre></div>

    </div>
<p>The above call is equivalent to the unbuffered call:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="n">somedef</span><span class="p">(</span><span class="mf">17</span><span class="p">,</span> <span class="s">&#39;hi&#39;</span><span class="p">,</span> <span class="n">use_paging</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span><span class="cp">}</span>
</pre></div>

    </div>




    </div>




            <a href="#filtering">back to section top</a>
    </div>


</html>
    
    
    <A name="unicode"></a>

    
    <div class="toolbar">
        <div class="prevnext">
            Previous: <a href="#filtering">Filtering and Buffering</a>

            |
            Next: <a href="#caching">Caching</a>
        </div>
        <h3><a href="documentation.html">Table of Contents</a></h3>
    </div>


    








    
    <A name="unicode"></a>
    
    <div class="section">
    

    <h3>The Unicode Chapter</h3>
    
    

<p>The Python language in the 2.x series supports two ways of representing string objects.  One is the <code>string</code> type and the other is the <code>unicode</code> type, both of which extend a type called <code>basestring</code>.  A key issue in Python, which is hopefully to be resolved in Python 3000, is that objects of type <code>string</code> (i.e. created from an expression such as <code>&quot;hello world&quot;</code>) contain no information regarding what <strong>encoding</strong> the data is stored in.   For this reason they are often referred to as <strong>byte strings</strong>.  The origins of this come from Python's background of being developed before the Unicode standard was even available, back when strings were C-style strings and were just that, a series of bytes.  Strings that had only values below 128 just happened to be <strong>ascii</strong> strings and were printable on the console, whereas strings with values above 128 would produce all kinds of graphical characters and bells.
</p>
<p>Contrast the Python <code>string</code> type with the Python <code>unicode</code> type.  Objects of this type are created whenever you say something like <code>u&quot;hello world&quot;</code>.  In this case, Python represents each character in the string internally using multiple bytes per character (something similar to UTF-16).  Whats important is that when using the <code>unicode</code> type to store strings, Python knows the data's encoding; its in its own internal format.  Whereas when using the <code>string</code> type, it does not.
</p>
<p>When Python attempts to treat a byte-string as a string, which means its attempting to compare/parse its characters, to coerce it into another encoding, or to decode it to a unicode object, it has to guess what the encoding is.  In this case, it will pretty much always guess the encoding as <code>ascii</code>...and if the bytestring contains bytes above value 128, you'll get an error.
</p>
<p>There is one operation that Python <em>can</em> do with a non-ascii bytestring, and its a great source of confusion:  it can dump the bytestring straight out to a stream or a file, with nary a care what the encoding is.  To Python, this is pretty much like dumping any other kind of binary data (like an image) to a stream somewhere.  So in a lot of cases, programs that embed all kinds of international characters and encodings into plain byte-strings (i.e. using <code>&quot;hello world&quot;</code> style literals) can fly right through their run, sending reams of strings out to whereever they are going, and the programmer, seeing the same output as was expressed in the input, is now under the illusion that his or her program is Unicode-compliant.  In fact, their program has no unicode awareness whatsoever, and similarly has no ability to interact with libraries that <em>are</em> unicode aware.
</p>
<p>The "pass through encoded data" scheme is what template languages like Cheetah and earlier versions of Myghty do by default.  Mako as of version 0.2 also supports this mode of operation using the "disable_unicode=True" flag.  However, when using Mako in its default mode of unicode-aware, it requires explicitness when dealing with non-ascii encodings.  Additionally, if you ever need to handle unicode strings and other kinds of encoding conversions more intelligently, the usage of raw bytestrings quickly becomes a nightmare, since you are sending the Python interpreter collections of bytes for which it can make no intelligent decisions with regards to encoding.
</p>
<p>In normal Mako operation, all parsed template constructs and output streams are handled internally as Python <code>unicode</code> objects.  Its only at the point of <code>render()</code> that this unicode stream is rendered into whatever the desired output encoding is.  The implication here is that the template developer must ensure that the encoding of all non-ascii templates is explicit, that all non-ascii-encoded expressions are in one way or another converted to unicode, and that the output stream of the template is handled as a unicode stream being encoded to some encoding.
</p>


    
    <A name="unicode_specifying"></a>
    
    <div class="subsection">
    

    <h3>Specifying the Encoding of a Template File</h3>
    
    

<p>This is the most basic encoding-related setting, and it is equivalent to Python's "magic encoding comment", as described in <a href='http://www.python.org/dev/peps/pep-0263/'>pep-0263</a>.  Any template that contains non-ascii characters  requires that this comment be present so that Mako can decode to unicode (and also make usage of Python's AST parsing services).  Mako's lexer will use this encoding in order to convert the template source into a <code>unicode</code> object before continuing its parsing:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">## -*- coding: utf-8 -*-</span>

Alors vous imaginez ma surprise, au lever du jour, quand une drôle de petit voix m’a réveillé. Elle disait: « S’il vous plaît… dessine-moi un mouton! »
</pre></div>

    </div>
<p>For the picky, the regular expression used is derived from that of the abovementioned pep:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="c">#.*coding[:=]\s*([-\w.]+).*\n</span>
</pre></div>

    </div>
<p>The lexer will convert to unicode in all cases, so that if any characters exist in the template that are outside of the specified encoding (or the default of <code>ascii</code>), the error will be immediate.
</p>
<p>As an alternative, the template encoding can be specified programmatically to either <code>Template</code> or <code>TemplateLookup</code> via the <code>input_encoding</code> parameter:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="n">t</span> <span class="o">=</span> <span class="n">TemplateLookup</span><span class="p">(</span><span class="n">directories</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;./&#39;</span><span class="p">],</span> <span class="n">input_encoding</span><span class="o">=</span><span class="s">&#39;utf-8&#39;</span><span class="p">)</span>
</pre></div>

    </div>
<p>The above will assume all located templates specify <code>utf-8</code> encoding, unless the template itself contains its own magic encoding comment, which takes precedence.
</p>



            <a href="#unicode">back to section top</a>
    </div>



    
    <A name="unicode_handling"></a>
    
    <div class="subsection">
    

    <h3>Handling Expressions</h3>
    
    

<p>The next area that encoding comes into play is in expression constructs.  By default, Mako's treatment of an expression like this:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="s">&quot;hello world&quot;</span><span class="cp">}</span>
</pre></div>

    </div>
<p>looks something like this:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="n">context</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="nb">unicode</span><span class="p">(</span><span class="s">&quot;hello world&quot;</span><span class="p">))</span>
</pre></div>

    </div>
<p>That is, <em></em>the output of all expressions is run through the <code>unicode</code> builtin<em></em>.  This is the default setting, and can be modified to expect various encodings.  The <code>unicode</code> step serves both the purpose of rendering non-string expressions into strings (such as integers or objects which contain <code>__str()__</code> methods), and to ensure that the final output stream is constructed as a unicode object.  The main implication of this is that <strong>any raw bytestrings that contain an encoding other than ascii must first be decoded to a Python unicode object</strong>.   It means you can't say this:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="s">&quot;voix m’a réveillé.&quot;</span><span class="cp">}</span>  <span class="cp">## error !</span>
</pre></div>

    </div>
<p>You must instead say this:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="s">u&quot;voix m’a réveillé.&quot;</span><span class="cp">}</span>  <span class="cp">## OK !</span>
</pre></div>

    </div>
<p>Similarly, if you are reading data from a file, or returning data from some object that is returning a Python bytestring containing a non-ascii encoding, you have to explcitly decode to unicode first, such as:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">${</span><span class="n">call_my_object</span><span class="p">()</span><span class="o">.</span><span class="n">decode</span><span class="p">(</span><span class="s">&#39;utf-8&#39;</span><span class="p">)</span><span class="cp">}</span>
</pre></div>

    </div>
<p>If you want a certain encoding applied to <em>all</em> expressions, override the <code>unicode</code> builtin with the <code>decode</code> builtin at the <code>Template</code> or <code>TemplateLookup</code> level:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="n">templatetext</span><span class="p">,</span> <span class="n">default_filters</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;decode.utf8&#39;</span><span class="p">])</span>
</pre></div>

    </div>
<p>Note that the built-in <code>decode</code> object is slower than the <code>unicode</code> function, since unlike <code>unicode</code> its not a Python builtin, and it also checks the type of the incoming data to determine if string conversion is needed first.
</p>
<p>The <code>default_filters</code> argument can be used to entirely customize the filtering process of expressions.  This argument is described in <a href="#filtering_expression_defaultfilters">The default_filters Argument</a>.
</p>



            <a href="#unicode">back to section top</a>
    </div>



    
    <A name="unicode_defining"></a>
    
    <div class="subsection">
    

    <h3>Defining Output Encoding</h3>
    
    

<p>Now that we have a template which produces a pure unicode output stream, all the hard work is done.  We can take the output and do anything with it.
</p>
<p>As stated in the "Usage" chapter, both <code>Template</code> and <code>TemplateLookup</code> accept <code>output_encoding</code> and <code>encoding_errors</code> parameters which can be used to encode the output in any Python supported codec:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="kn">from</span> <span class="nn">mako.template</span> <span class="kn">import</span> <span class="n">Template</span>
<span class="kn">from</span> <span class="nn">mako.lookup</span> <span class="kn">import</span> <span class="n">TemplateLookup</span>

<span class="n">mylookup</span> <span class="o">=</span> <span class="n">TemplateLookup</span><span class="p">(</span><span class="n">directories</span><span class="o">=</span><span class="p">[</span><span class="s">&#39;/docs&#39;</span><span class="p">],</span> <span class="n">output_encoding</span><span class="o">=</span><span class="s">&#39;utf-8&#39;</span><span class="p">,</span> <span class="n">encoding_errors</span><span class="o">=</span><span class="s">&#39;replace&#39;</span><span class="p">)</span>

<span class="n">mytemplate</span> <span class="o">=</span> <span class="n">mylookup</span><span class="o">.</span><span class="n">get_template</span><span class="p">(</span><span class="s">&quot;foo.txt&quot;</span><span class="p">)</span>
<span class="k">print</span> <span class="n">mytemplate</span><span class="o">.</span><span class="n">render</span><span class="p">()</span>
</pre></div>

    </div>
<p>And <code>render_unicode()</code> will return the template output as a Python <code>unicode</code> object:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="k">print</span> <span class="n">mytemplate</span><span class="o">.</span><span class="n">render_unicode</span><span class="p">()</span>
</pre></div>

    </div>
<p>The above method disgards the output encoding keyword argument; you can encode yourself by saying:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="k">print</span> <span class="n">mytemplate</span><span class="o">.</span><span class="n">render_unicode</span><span class="p">()</span><span class="o">.</span><span class="n">encode</span><span class="p">(</span><span class="s">&#39;utf-8&#39;</span><span class="p">,</span> <span class="s">&#39;replace&#39;</span><span class="p">)</span>
</pre></div>

    </div>


    
    <A name="unicode_defining_buffer"></a>
    
    <div class="subsection">
    

    <h3>Buffer Selection</h3>
    
    

<p>Mako does play some games with the style of buffering used internally, to maximize performance.  Since the buffer is by far the most heavily used object in a render operation, its important!
</p>
<p>When calling <code>render()</code> on a template that does not specify any output encoding (i.e. its <code>ascii</code>), Python's <code>cStringIO</code> module, which cannot handle encoding of non-ascii <code>unicode</code> objects (even though it can send raw bytestrings through), is used for buffering.  Otherwise, a custom Mako class called <code>FastEncodingBuffer</code> is used, which essentially is a super dumbed-down version of <code>StringIO</code> that gathers all strings into a list and uses <code>u''.join(elements)</code> to produce the final output - its markedly faster than <code>StringIO</code>.
</p>



    </div>




            <a href="#unicode">back to section top</a>
    </div>



    
    <A name="unicode_saying"></a>
    
    <div class="subsection">
    

    <h3>Saying to Heck with it:  Disabling the usage of Unicode entirely</h3>
    
    

<p>Some segements of Mako's userbase choose to make no usage of Unicode whatsoever, and instead would prefer the "passthru" approach; all string expressions in their templates return encoded bytestrings, and they would like these strings to pass right through.   The generated template module is also in the same encoding as the template and additionally carries Python's "magic encoding comment" at the top.   The only advantage to this approach is that templates need not use <code>u&quot;&quot;</code> for literal strings; there's an arguable speed improvement as well since raw bytestrings generally perform slightly faster than unicode objects in Python.  For these users, they will have to get used to using Unicode when Python 3000 becomes the standard, but for now they can hit the <code>disable_unicode=True</code> flag, introduced in version 0.2 of Mako, as so:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="c"># -*- encoding:utf-8 -*-</span>
<span class="kn">from</span> <span class="nn">mako.template</span> <span class="kn">import</span> <span class="n">Template</span>

<span class="n">t</span> <span class="o">=</span> <span class="n">Template</span><span class="p">(</span><span class="s">&quot;drôle de petit voix m’a réveillé.&quot;</span><span class="p">,</span> <span class="n">disable_unicode</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">input_encoding</span><span class="o">=</span><span class="s">&#39;utf-8&#39;</span><span class="p">)</span>
<span class="k">print</span> <span class="n">t</span><span class="o">.</span><span class="n">code</span>
</pre></div>

    </div>
<p>The generated module source code will contain elements like these:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="c"># -*- encoding:utf-8 -*-</span>
<span class="c">#  ...more generated code ...</span>

<span class="k">def</span> <span class="nf">render_body</span><span class="p">(</span><span class="n">context</span><span class="p">,</span><span class="o">**</span><span class="n">pageargs</span><span class="p">):</span>
    <span class="n">context</span><span class="o">.</span><span class="n">caller_stack</span><span class="o">.</span><span class="n">push_frame</span><span class="p">()</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">__M_locals</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">pageargs</span><span class="o">=</span><span class="n">pageargs</span><span class="p">)</span>
        <span class="c"># SOURCE LINE 1</span>
        <span class="n">context</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s">&#39;dr</span><span class="se">\xc3\xb4</span><span class="s">le de petit voix m</span><span class="se">\xe2\x80\x99</span><span class="s">a r</span><span class="se">\xc3\xa9</span><span class="s">veill</span><span class="se">\xc3\xa9</span><span class="s">.&#39;</span><span class="p">)</span>
        <span class="k">return</span> <span class="s">&#39;&#39;</span>
    <span class="k">finally</span><span class="p">:</span>
        <span class="n">context</span><span class="o">.</span><span class="n">caller_stack</span><span class="o">.</span><span class="n">pop_frame</span><span class="p">()</span>
</pre></div>

    </div>
<p>Where above you can see that the <code>encoding</code> magic source comment is at the top, and the string literal used within <code>context.write</code> is a regular bytestring. 
</p>
<p>When <code>disable_unicode=True</code> is turned on, the <code>default_filters</code> argument which normally defaults to <code>[&quot;unicode&quot;]</code> now defaults to <code>[&quot;str&quot;]</code> instead.  Setting default_filters to the empty list <code>[]</code> can remove the overhead of the <code>str</code> call.  Also, in this mode you <strong>cannot</strong> safely call <code>render_unicode()</code> - you'll get unicode/decode errors.
</p>
<p><strong>Rules for using disable_unicode=True</strong>
</p>
<ul>
 <li>
     don't use this mode unless you really, really want to and you absolutely understand what you're doing
 </li>

 <li>
     don't use this option just because you don't want to learn to use Unicode properly; we aren't supporting user issues in this mode of operation.  We will however offer generous help for the vast majority of users who stick to the Unicode program.
 </li>

 <li>
     it's extremely unlikely this mode of operation will be present in the Python 3000 version of Mako since P3K strings are unicode objects by default; bytestrings are relegated to a "bytes" type that is not intended for dealing with text.
 </li>
</ul>




    </div>




            <a href="#unicode">back to section top</a>
    </div>


</html>
    
    
    <A name="caching"></a>

    
    <div class="toolbar">
        <div class="prevnext">
            Previous: <a href="#unicode">The Unicode Chapter</a>

        </div>
        <h3><a href="documentation.html">Table of Contents</a></h3>
    </div>


    








    
    <A name="caching"></a>
    
    <div class="section">
    

    <h3>Caching</h3>
    
    

<p>Any template or component can be cached using the <code>cache</code> argument to the <code>&lt;%page&gt;</code> or <code>&lt;%def&gt;</code> directives:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">page</span> <span class="na">cached=</span><span class="s">&quot;True&quot;</span><span class="cp">/&gt;</span>

template text
</pre></div>

    </div>
<p>The above template, after being executed the first time, will store its content within a cache that by default is scoped within memory.  Subsequent calls to the template's <code>render()</code> method will return content directly from the cache.  When the <code>Template</code> object itself falls out of scope, its corresponding cache is garbage collected along with the template.
</p>
<p>Caching requires that the <code>beaker</code> package be installed on the system.
</p>
<p>The caching flag and all its options can be used with the <code>&lt;%def&gt;</code> tag.  <br></br>
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">def</span> <span class="na">name=</span><span class="s">&quot;mycomp&quot;</span> <span class="na">cached=</span><span class="s">&quot;True&quot;</span> <span class="na">cache_timeout=</span><span class="s">&quot;30&quot;</span> <span class="na">cache_type=</span><span class="s">&quot;memory&quot;</span><span class="cp">&gt;</span>
    other text
<span class="cp">&lt;/%</span><span class="nb">def</span><span class="cp">&gt;</span>
</pre></div>

    </div>


    
    <A name="caching_arguments"></a>
    
    <div class="subsection">
    

    <h3>Cache arguments</h3>
    
    

<p>The various cache arguments are cascaded from their default values, to the arguments specified programmatically to the <code>Template</code> or its originating <code>TemplateLookup</code>, then to those defined in the <code>&lt;%page&gt;</code> tag of an individual template, and finally to an individual <code>&lt;%def&gt;</code> tag within the template.  This means you can define, for example, a cache type of <code>dbm</code> on your <code>TemplateLookup</code>, a cache timeout of 60 seconds in a particular template's <code>&lt;%page&gt;</code> tag, and within one of that template's <code>&lt;%def&gt;</code> tags <code>cache=True</code>, and that one particular def will then cache its data using a <code>dbm</code> cache and a data timeout of 60 seconds.
</p>
<p>The options available are:
</p>
<ul>
 <li><p>cached="False|True" - turn caching on
</p>

 </li>

 <li><p>cache_timeout - number of seconds in which to invalidate the cached data.  after this timeout, the content is re-generated on the next call.
</p>

 </li>

 <li><p>cache_type - type of caching.  <code>memory</code>, <code>file</code>, <code>dbm</code>, or <code>memcached</code>.
</p>

 </li>

 <li><p>cache_url - (only used for <code>memcached</code> but required) a single IP address or a semi-colon separated list of IP address of memcache servers to use.
</p>

 </li>

 <li><p>cache_dir  - In the case of the <code>file</code> and <code>dbm</code> cache types, this is the filesystem directory with which to store data files.  If this option is not present, the value of <code>module_directory</code> is used (i.e. the directory where compiled template modules are stored).  If neither option is available an exception is thrown.
   In the case of the <code>memcached</code> type, this attribute is required and it's used to store the lock files.
</p>

 </li>

 <li><p>cache_key - the "key" used to uniquely identify this content in the cache.  the total namespace of keys within the cache is local to the current template, and the default value of "key" is the name of the def which is storing its data.  It is an evaluable tag, so you can put a Python expression to calculate the value of the key on the fly.  For example, heres a page that caches any page which inherits from it, based on the filename of the calling template:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span><span class="nb">page</span> <span class="na">cached=</span><span class="s">&quot;True&quot;</span> <span class="na">cache_key=</span><span class="s">&quot;${self.filename}&quot;</span><span class="cp">/&gt;</span>

<span class="cp">${</span><span class="n">next</span><span class="o">.</span><span class="n">body</span><span class="p">()</span><span class="cp">}</span>

<span class="cp">## rest of template</span>
</pre></div>

    </div>

 </li>
</ul>



            <a href="#caching">back to section top</a>
    </div>



    
    <A name="caching_accessing"></a>
    
    <div class="subsection">
    

    <h3>Accessing the Cache</h3>
    
    

<p>The <code>Template</code>, as well as any template-derived namespace, has an accessor called <code>cache</code> which returns the <code>Cache</code> object for that template.   This object is a facade on top of the Beaker internal cache object, and provides some very rudimental capabilities, such as the ability to get and put arbitrary values:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="cp">&lt;%</span>
    <span class="n">local</span><span class="o">.</span><span class="n">cache</span><span class="o">.</span><span class="n">put</span><span class="p">(</span><span class="s">&quot;somekey&quot;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="s">&quot;memory&quot;</span><span class="p">,</span> <span class="s">&quot;somevalue&quot;</span><span class="p">)</span>
<span class="cp">%&gt;</span>
</pre></div>

    </div>
<p>Above, the cache associated with the <code>local</code> namespace is accessed and a key is placed within a memory cache.
</p>
<p>More commonly the <code>cache</code> object is used to invalidate cached sections programmatically:
</p>

    
    

    <div class="code">
        <div class="highlight"><pre><span class="n">template</span> <span class="o">=</span> <span class="n">lookup</span><span class="o">.</span><span class="n">get_template</span><span class="p">(</span><span class="s">&#39;/sometemplate.html&#39;</span><span class="p">)</span>

<span class="c"># invalidate the &quot;body&quot; of the template</span>
<span class="n">template</span><span class="o">.</span><span class="n">cache</span><span class="o">.</span><span class="n">invalidate_body</span><span class="p">()</span>

<span class="c"># invalidate an individual def</span>
<span class="n">template</span><span class="o">.</span><span class="n">cache</span><span class="o">.</span><span class="n">invalidate_def</span><span class="p">(</span><span class="s">&#39;somedef&#39;</span><span class="p">)</span>

<span class="c"># invalidate an arbitrary key</span>
<span class="n">template</span><span class="o">.</span><span class="n">cache</span><span class="o">.</span><span class="n">invalidate</span><span class="p">(</span><span class="s">&#39;somekey&#39;</span><span class="p">)</span>
</pre></div>

    </div>




    </div>




            <a href="#caching">back to section top</a>
    </div>


</html>







</body>
</html>