This section documents the package as a Python library. To learn about the page template language, consult the language reference.
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.basedir(__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>'
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%.
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()" />
This sections describes new features, improvements and changes from 1.x to 2.x.
This series features a new, custom-built parser, implemented in pure Python. It parses both HTML and XML inputs (the previous parser relied on the expat system library and was more strict about its input).
The main benefit of the new parser is that the compiler is now able to point to the source location of parse- and compilation errors much more accurately. This should be a great aid in debugging these errors.
The 2.x engine matches the output of the reference implementation more closely (usually exactly). There are less differences altogether; for instance, the method of escaping TALES expression (usually a semicolon) has been changed to match that of the reference implementation.
This series also introduces a number of new language features:
The template classes have been refactored and simplified allowing better reuse of code and more intuitive APIs on the lower levels.
The expression engine has been redesigned to make it easier to understand and extend. The new engine is based on the ast module (available since Python 2.6; backports included for Python 2.5). This means that expression compilers now need to return a valid list of AST statements that include an assignment to the target node.
The new compiler has been optimized for complex templates. As a result, in the benchmark suite included with the package, this compiler scores about half of the 1.x series. For most real world applications, the engine should still perform as well as the 1.x series.
This section describes the documented API of the library.
Use the PageTemplate* template classes to define a template from a string or file input:
Constructor for the page template language.
Takes a string input as the only positional argument:
template = PageTemplate("<div>Hello, ${name}.</div>")
Configuration (keyword arguments):
default_expression
Set the default expression type. The default setting is python.encoding
The default text substitution value is a unicode string on Python 2 or simply string on Python 3.
Pass an encoding to allow encoded byte string input (e.g. UTF-8).
literal_false
Attributes are not dropped for a value of False. Instead, the value is coerced to a string.
This setting exists to provide compatibility with the reference implementation.
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.
translate
Use this option to set a translation function.
Example:
def translate(msgid, domain=None, mapping=None, default=None): ... return translationNote that if target_language is provided at render time, the translation function must support this argument.
Output is unicode on Python 2 and string on Python 3.
Note: The remaining classes take the same general configuration arguments.
Render template to string.
The encoding and translate arguments are documented in the template class constructor. If passed to this method, they are used instead of the class defaults.
Additional arguments:
target_language
This argument will be partially applied to the translation function.
An alternative is thus to simply provide a custom translation function which includes this information or relies on a different mechanism.
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.
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.
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:
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")
Load and return a template file.
The format parameter determines will parse the file. Valid options are xml and text.
For advanced integration, the compiler module provides support for dynamic expression evaluation:
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)
>>> evaluate = ExpressionEvaluator(engine, {
... 'foo': 'bar',
... })
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'