class documentation

class Template(object):

Known subclasses: mako.template.DefTemplate, mako.template.ModuleTemplate

View In Hierarchy

Represents a compiled template.

.Template includes a reference to the original template source (via the .source attribute) as well as the source code of the generated Python module (i.e. the .code attribute), as well as a reference to an actual Python module.

.Template is constructed using either a literal string representing the template text, or a filename representing a filesystem path to a source file.

Parameters
texttextual template source. This argument is mutually exclusive versus the filename parameter.
filenamefilename of the source template. This argument is mutually exclusive versus the text parameter.
buffer​_filtersstring list of filters to be applied to the output of %defs which are buffered, cached, or otherwise filtered, after all filters defined with the %def itself have been applied. Allows the creation of default expression filters that let the output of return-valued %defs "opt out" of that filtering via passing special attributes or objects.
bytestring​_passthrough

When True, and output_encoding is set to None, and .Template.render is used to render, the StringIO or cStringIO buffer will be used instead of the default "fast" buffer. This allows raw bytestrings in the output stream, such as in expressions, to pass straight through to the buffer. This flag is forced to True if disable_unicode is also configured.

New in version 0.4: Added to provide the same behavior as that of the previous series.
cache​_argsDictionary of cache configuration arguments that will be passed to the .CacheImpl. See :ref:`caching_toplevel`.
cache​_dir
Deprecated since version 0.6: Use the 'dir' argument in the cache_args dictionary. See :ref:`caching_toplevel`.
cache​_enabledBoolean flag which enables caching of this template. See :ref:`caching_toplevel`.
cache​_implString name of a .CacheImpl caching implementation to use. Defaults to 'beaker'.
cache​_type
Deprecated since version 0.6: Use the 'type' argument in the cache_args dictionary. See :ref:`caching_toplevel`.
cache​_url
Deprecated since version 0.6: Use the 'url' argument in the cache_args dictionary. See :ref:`caching_toplevel`.
default​_filtersList of string filter names that will be applied to all expressions. See :ref:`filtering_default_filters`.
disable​_unicodeDisables all awareness of Python Unicode objects. See :ref:`unicode_disabled`.
enable​_loopWhen True, enable the loop context variable. This can be set to False to support templates that may be making usage of the name "loop". Individual templates can re-enable the "loop" context by placing the directive enable_loop="True" inside the <%page> tag -- see :ref:`migrating_loop`.
encoding​_errorsError parameter passed to encode() when string encoding is performed. See :ref:`usage_unicode`.
error​_handler

Python callable which is called whenever compile or runtime exceptions occur. The callable is passed the current context as well as the exception. If the callable returns True, the exception is considered to be handled, else it is re-raised after the function completes. Is used to provide custom error-rendering functions.

See Also

:paramref:`.Template.include_error_handler` - include-specific error handler function

format​_exceptionsif True, exceptions which occur during the render phase of this template will be caught and formatted into an HTML error page, which then becomes the rendered result of the .render call. Otherwise, runtime exceptions are propagated outwards.
importsString list of Python statements, typically individual "import" lines, which will be placed into the module level preamble of all generated Python modules. See the example in :ref:`filtering_default_filters`.
future​_importsString list of names to import from __future__. These will be concatenated into a comma-separated string and inserted into the beginning of the template, e.g. futures_imports=['FOO', 'BAR'] results in from __future__ import FOO, BAR. If you're interested in using features like the new division operator, you must use future_imports to convey that to the renderer, as otherwise the import will not appear as the first executed statement in the generated code and will therefore not have the desired effect.
include​_error​_handler

An error handler that runs when this template is included within another one via the <%include> tag, and raises an error. Compare to the :paramref:`.Template.error_handler` option.

New in version 1.0.6.

See Also

:paramref:`.Template.error_handler` - top-level error handler function

input​_encodingEncoding of the template's source code. Can be used in lieu of the coding comment. See :ref:`usage_unicode` as well as :ref:`unicode_toplevel` for details on source encoding.
lookupa .TemplateLookup instance that will be used for all file lookups via the <%namespace>, <%include>, and <%inherit> tags. See :ref:`usage_templatelookup`.
module​_directoryFilesystem location where generated Python module files will be placed.
module​_filenameOverrides the filename of the generated Python module file. For advanced usage only.
module​_writer

A callable which overrides how the Python module is written entirely. The callable is passed the encoded source content of the module and the destination path to be written to. The default behavior of module writing uses a tempfile in conjunction with a file move in order to make the operation atomic. So a user-defined module writing function that mimics the default behavior would be:

import tempfile
import os
import shutil

def module_writer(source, outputpath):
    (dest, name) = \\
        tempfile.mkstemp(
            dir=os.path.dirname(outputpath)
        )

    os.write(dest, source)
    os.close(dest)
    shutil.move(name, outputpath)

from mako.template import Template
mytemplate = Template(
                filename="index.html",
                module_directory="/path/to/modules",
                module_writer=module_writer
            )

The function is provided for unusual configurations where certain platform-specific permissions or other special steps are needed.

output​_encodingThe encoding to use when .render is called. See :ref:`usage_unicode` as well as :ref:`unicode_toplevel`.
preprocessorPython callable which will be passed the full template source before it is parsed. The return result of the callable will be used as the template source code.
lexer​_cls

A .Lexer class used to parse the template. The .Lexer class is used by default.

New in version 0.7.4.
strict​_undefined

Replaces the automatic usage of UNDEFINED for any undeclared variables not located in the .Context with an immediate raise of NameError. The advantage is immediate reporting of missing variables which include the name.

New in version 0.3.6.
uristring URI or other identifier for this template. If not provided, the uri is generated from the filesystem path, or from the in-memory identity of a non-file-based template. The primary usage of the uri is to provide a key within .TemplateLookup, as well as to generate the file path of the generated Python module file, if module_directory is specified.
Method get​_def Return a def of this template as a .DefTemplate.
Method list​_defs return a list of defs in the template.
Method render Render the output of this template as a string.
Method render​_context Render this .Template with the given context.
Method render​_unicode Render the output of this template as a unicode object.
Method __init__ Undocumented
Method ​_compile​_from​_file Undocumented
Method ​_get​_def​_callable Undocumented
Method ​_setup​_cache​_args Undocumented
Method has​_def Undocumented
Instance Variable ​_code Undocumented
Instance Variable ​_source Undocumented
Instance Variable buffer​_filters Undocumented
Instance Variable bytestring​_passthrough Undocumented
Instance Variable cache​_args Undocumented
Instance Variable cache​_enabled Undocumented
Instance Variable cache​_impl Undocumented
Instance Variable callable​_ Undocumented
Instance Variable default​_filters Undocumented
Instance Variable disable​_unicode Undocumented
Instance Variable enable​_loop Undocumented
Instance Variable encoding​_errors Undocumented
Instance Variable error​_handler Undocumented
Instance Variable filename Undocumented
Instance Variable format​_exceptions Undocumented
Instance Variable future​_imports Undocumented
Instance Variable imports Undocumented
Instance Variable include​_error​_handler Undocumented
Instance Variable input​_encoding Undocumented
Instance Variable lexer​_cls Undocumented
Instance Variable lookup Undocumented
Instance Variable module Undocumented
Instance Variable module​_directory Undocumented
Instance Variable module​_id Undocumented
Instance Variable module​_writer Undocumented
Instance Variable output​_encoding Undocumented
Instance Variable preprocessor Undocumented
Instance Variable strict​_undefined Undocumented
Instance Variable uri Undocumented
Property cache Undocumented
Property cache​_dir Undocumented
Property cache​_type Undocumented
Property cache​_url Undocumented
Property code Return the module source code for this .Template.
Property last​_modified Undocumented
Property reserved​_names Undocumented
Property source Return the template source code for this .Template.
def get_def(self, name):
Return a def of this template as a .DefTemplate.
def list_defs(self):

return a list of defs in the template.

New in version 1.0.4.
def render(self, *args, **data):

Render the output of this template as a string.

If the template specifies an output encoding, the string will be encoded accordingly, else the output is raw (raw output uses cStringIO and can't handle multibyte characters). A .Context object is created corresponding to the given data. Arguments that are explicitly declared by this template's internal rendering method are also pulled from the given *args, **data members.

def render_context(self, context, *args, **kwargs):

Render this .Template with the given context.

The data is written to the context's buffer.

def render_unicode(self, *args, **data):
Render the output of this template as a unicode object.
def __init__(self, text=None, filename=None, uri=None, format_exceptions=False, error_handler=None, lookup=None, output_encoding=None, encoding_errors='strict', module_directory=None, cache_args=None, cache_impl='beaker', cache_enabled=True, cache_type=None, cache_dir=None, cache_url=None, module_filename=None, input_encoding=None, disable_unicode=False, module_writer=None, bytestring_passthrough=False, default_filters=None, buffer_filters=(), strict_undefined=False, imports=None, future_imports=None, enable_loop=True, preprocessor=None, lexer_cls=None, include_error_handler=None):
def _compile_from_file(self, path, filename):

Undocumented

def _get_def_callable(self, name):

Undocumented

def _setup_cache_args(self, cache_impl, cache_enabled, cache_args, cache_type, cache_dir, cache_url):

Undocumented

def has_def(self, name):

Undocumented

_code =

Undocumented

_source =

Undocumented

buffer_filters =

Undocumented

bytestring_passthrough =
cache_args =

Undocumented

cache_enabled =

Undocumented

cache_impl =

Undocumented

callable_ =
default_filters: list[str] =

Undocumented

disable_unicode =

Undocumented

enable_loop =
encoding_errors =
error_handler =
filename =

Undocumented

format_exceptions =
future_imports =

Undocumented

imports =

Undocumented

include_error_handler =
input_encoding =

Undocumented

lexer_cls =

Undocumented

lookup =
module =
module_directory =

Undocumented

module_id =

Undocumented

module_writer =

Undocumented

output_encoding =
preprocessor =

Undocumented

strict_undefined =

Undocumented

uri =

Undocumented

Undocumented

@property
cache_dir =

Undocumented

@property
cache_type =

Undocumented

@property
cache_url =

Undocumented

@property
code =
Return the module source code for this .Template.
@property
last_modified =

Undocumented

@util.memoized_property
reserved_names =

Undocumented

@property
source =
Return the template source code for this .Template.