Library Documentation

This section documents the package as a Python library. To learn about the page template language, consult the language reference.

Getting started

There are several template constructor classes available, one for each of the combinations text or xml, and string or file.

The file-based constructor requires an absolute path. To set up a templates directory once, use the template loader class:

import os

path = os.path.dirname(__file__)

from chameleon import PageTemplateLoader
templates = PageTemplateLoader(os.path.join(path, "templates"))

Then, to load a template relative to the provided path, use dictionary syntax:

template = templates['hello.pt']

Alternatively, use the appropriate template class directly. Let’s try with a string input:

from chameleon import PageTemplate
template = PageTemplate("<div>Hello, ${name}.</div>")

All template instances are callable. Provide variables by keyword argument:

>>> template(name='John')
'<div>Hello, John.</div>'

Performance

The template engine compiles (or translates) template source code into Python byte-code. In simple templates this yields an increase in performance of about 7 times in comparison to the reference implementation.

In benchmarks for the content management system Plone, switching to Chameleon yields a request to response improvement of 20-50%.

Extension

You can extend the language through the expression engine by writing your own expression compiler.

Let’s try and write an expression compiler for an expression type that will simply uppercase the supplied value. We’ll call it upper.

You can write such a compiler as a closure:

import ast

def uppercase_expression(string):
    def compiler(target, engine):
        uppercased = self.string.uppercase()
        value = ast.Str(uppercased)
        return [ast.Assign(targets=[target], value=value)]
    return compiler

To make it available under a certain prefix, we’ll add it to the expression types dictionary.

from chameleon import PageTemplate
PageTemplate.expression_types['upper'] = uppercase_expression

Alternatively, you could subclass the template class and set the attribute expression_types to a dictionary that includes your expression:

from chameleon import PageTemplateFile
from chameleon.tales import PythonExpr

class MyPageTemplateFile(PageTemplateFile):
    expression_types = {
        'python': PythonExpr,
        'upper': uppercase_expression
        }

You can now uppercase strings natively in your templates:

<div tal:content="upper: hello, world" />

It’s probably best to stick with a Python expression:

<div tal:content="'hello, world'.upper()" />

API reference

This section describes the documented API of the library.

Templates

Use the PageTemplate* template classes to define a template from a string or file input:

class chameleon.PageTemplate(body, **config)

Constructor for the page template language.

Takes a string input as the only positional argument:

template = PageTemplate("<div>Hello, ${name}.</div>")

Configuration (keyword arguments):

auto_reload

Enables automatic reload of templates. This is mostly useful in a development mode since it takes a significant performance hit.

default_expression

Set the default expression type. The default setting is python.

encoding

The default text substitution value is a string.

Pass an encoding to allow encoded byte string input (e.g. UTF-8).

boolean_attributes

Attributes included in this set are treated as booleans: if a true value is provided, the attribute value is the attribute name, e.g.:

boolean_attributes = {"selected"}

If we insert an attribute with the name “selected” and provide a true value, the attribute will be rendered:

selected="selected"

If a false attribute is provided (including the empty string), the attribute is dropped.

The special return value default drops or inserts the attribute based on the value element attribute value.

The default setting is to autodetect if we’re in HTML-mode and provide the standard set of boolean attributes for this document type.

translate

Use this option to set a translation function.

Example:

def translate(msgid, domain=None, mapping=None, default=None,
              context=None):
    ...
    return translation

Note that if target_language is provided at render time, the translation function must support this argument.

implicit_i18n_translate

Enables implicit translation for text appearing inside elements. Default setting is False.

While implicit translation does work for text that includes expression interpolation, each expression must be simply a variable name (e.g. ${foo}); otherwise, the text will not be marked for translation.

implicit_i18n_attributes

Any attribute contained in this set will be marked for implicit translation. Each entry must be a lowercase string.

Example:

implicit_i18n_attributes = set(['alt', 'title'])

on_error_handler

This is an optional exception handler that is invoked during the “on-error” fallback block.

strict

Enabled by default. If disabled, expressions are only required to be valid at evaluation time.

This setting exists to provide compatibility with the reference implementation which compiles expressions at evaluation time.

trim_attribute_space

If set, additional attribute whitespace will be stripped.

restricted_namespace

True by default. If set False, ignored all namespace except chameleon default namespaces. It will be useful working with attributes based javascript template renderer like VueJS.

Example:

<div v-bind:id=”dynamicId”></div> <button v-on:click=”greet”>Greet</button> <button @click=”greet”>Greet</button>

tokenizer

None by default. If provided, this tokenizer is used instead of the default (which is selected based on the template mode parameter.)

value_repr

This can be used to override the default value representation function which is used to format values when formatting an exception output. The function must not raise an exception (it should be safe to call with any value).

default_marker

This default marker is used as the marker object bound to the default name available to any expression. The semantics is such that if an expression evaluates to the marker object, the default action is used; for an attribute expression, this is the static attribute text; for an element this is the static element text. If there is no static text then the default action is similar to an expression result of None.

Output is of type str.

Note: The remaining classes take the same general configuration arguments.

render(encoding=None, **_kw)

Render template to string.

If providd, the encoding argument overrides the template default value.

Additional keyword arguments are passed as template variables.

In addition, some also have a special meaning:

translate

This keyword argument will override the default template translate function.

target_language

This will be used as the default argument to the translate function if no i18n:target value is provided.

If not provided, the translate function will need to negotiate a language based on the provided context.

class chameleon.PageTemplateFile(filename, **config)

File-based constructor.

Takes a string input as the only positional argument:

template = PageTemplateFile(absolute_path)

Note that the file-based template class comes with the expression type load which loads templates relative to the provided filename.

Below are listed the configuration arguments specific to file-based templates; see the string-based template class for general options and documentation:

Configuration (keyword arguments):

loader_class

The provided class will be used to create the template loader object. The default implementation supports relative and absolute path specs.

The class must accept keyword arguments search_path (sequence of paths to search for relative a path spec) and default_extension (if provided, this should be added to any path spec).

prepend_relative_search_path

Inserts the path relative to the provided template file path into the template search path.

The default setting is True.

search_path

If provided, this is used as the search path for the load: expression. It must be a string or an iterable yielding a sequence of strings.

class chameleon.PageTextTemplate(body, **config)

Text-based template class.

Takes a non-XML input:

template = PageTextTemplate("Hello, ${name}.")

This is similar to the standard library class string.Template, but uses the expression engine to substitute variables.

class chameleon.PageTextTemplateFile(spec, search_path=None, loader_class=<class 'chameleon.loader.TemplateLoader'>, **config)

File-based constructor.

Loader

Some systems have framework support for loading templates from files. The following loader class is directly compatible with the Pylons framework and may be adapted to other frameworks:

class chameleon.PageTemplateLoader(search_path=None, default_extension=None, **config)

Load templates from search_path (must be a string or a list of strings):

templates = PageTemplateLoader(path)
example = templates['example.pt']

If default_extension is provided, this will be added to inputs that do not already have an extension:

templates = PageTemplateLoader(path, ".pt")
example = templates['example']

Any additional keyword arguments will be passed to the template constructor:

templates = PageTemplateLoader(path, debug=True, encoding="utf-8")
PageTemplateLoader.load(filename, format=None)

Load and return a template file.

The format parameter determines will parse the file. Valid options are xml and text.

Exceptions

Chameleon may raise exceptions during both the cooking and the rendering phase, but those raised during the cooking phase (parse and compile) all inherit from a single base class:

class chameleon.TemplateError(msg, token)

This exception is the base class of all exceptions raised by the template engine in the case where a template has an error.

It may be raised during rendering since templates are processed lazily (unless eager loading is enabled).

An error that occurs during the rendering of a template is wrapped in an exception class to disambiguate the two cases:

class chameleon.RenderError(*args)

Indicates an exception that resulted from the evaluation of an expression in a template.

A complete traceback is attached to the exception beginning with the expression that resulted in the error. The traceback includes a string representation of the template variable scope for further reference.

Expressions

For advanced integration, the compiler module provides support for dynamic expression evaluation:

class chameleon.compiler.ExpressionEvaluator(engine, builtins)

Evaluates dynamic expression.

This is not particularly efficient, but supported for legacy applications.

>>> from chameleon import tales
>>> parser = tales.ExpressionParser({'python': tales.PythonExpr}, 'python')
>>> engine = functools.partial(ExpressionEngine, parser)
>>> evaluator = ExpressionEvaluator(engine, {
...     'foo': 'bar',
... })

We’ll use the following convenience function to test the expression evaluator. >>> from chameleon.utils import Scope >>> def evaluate(d, *args): … return evaluator(Scope(d), *args)

The evaluation function is passed the local and remote context, the expression type and finally the expression.

>>> evaluate({'boo': 'baz'}, {}, 'python', 'foo + boo')
'barbaz'

The cache is now primed:

>>> evaluate({'boo': 'baz'}, {}, 'python', 'foo + boo')
'barbaz'

Note that the call method supports currying of the expression argument:

>>> python = evaluate({'boo': 'baz'}, {}, 'python')
>>> python('foo + boo')
'barbaz'