core.templates

Integrates the Chameleon template language.

This is basically a copy of more.chameleon, with the additional inclusion of a gettext translation function defined by onegov.core.i18n.

To use a chameleon template, applications have to specify the templates directory, in addition to inheriting from onegov.core.framework.Framework.

For example:

from onegov.core.framework import Framework

class App(Framework):
    pass

@App.template_directory()
def get_template_directory():
    return 'templates'

@App.path()
class Root:
    pass

@App.html(model=Root, template='index.pt')
def view_root(self, request):
    return {
        'title': 'The Title'
    }

The folder can either be a directory relative to the app class or an absolute path.

Attributes

_T

AUTO_RELOAD

BOOLEAN_HTML_ATTRS

Classes

PageTemplate

Constructor for the page template language.

PageTemplateFile

File-based constructor.

TemplateLoader

Extends the default page template loader with the ability to

MacrosLookup

Takes a list of search paths and provides a lookup for macros.

Functions

get_default_vars(→ dict[str, Any])

get_template_loader(→ TemplateLoader)

Returns the Chameleon template loader for templates with the extension

get_chameleon_render(→ Callable[[dict[str, Any], ...)

Returns the Chameleon template renderer for the required template.

render_template(→ markupsafe.Markup)

Renders the given template. Use this if you need to get the rendered

render_macro(→ markupsafe.Markup)

Renders a chameleon.zpt.template.Macro like this:

Module Contents

core.templates._T[source]
core.templates.AUTO_RELOAD[source]
core.templates.BOOLEAN_HTML_ATTRS[source]
class core.templates.PageTemplate(*args: Any, **kwargs: Any)[source]

Bases: chameleon.PageTemplate

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, target_language=None):
    ...
    return translation

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.

class core.templates.PageTemplateFile(*args: Any, **kwargs: Any)[source]

Bases: chameleon.PageTemplateFile

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.

package_name

If provided, the template is loaded relative to the package contents.

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.

core.templates.get_default_vars(request: core.request.CoreRequest, content: Mapping[str, Any], suppress_global_variables: bool = False) dict[str, Any][source]
class core.templates.TemplateLoader(search_path: collections.abc.Sequence[str] | str | None = None, default_extension: str | None = None, *, formats: _FormatsMapping | None = None, **kwargs: Any)[source]

Bases: chameleon.PageTemplateLoader

Extends the default page template loader with the ability to lookup macros in various folders.

formats[source]
property macros: MacrosLookup[source]
property mail_macros: MacrosLookup[source]
class core.templates.MacrosLookup(search_paths: Iterable[StrPath], name: str = 'macros.pt')[source]

Takes a list of search paths and provides a lookup for macros.

This means that when a macro is access through this lookup, it will travel up the search path of the template loader, to look for the macro and return with the first match.

As a result, it is possible to have a macros.pt file in each search path and have them act as if they were one file, with macros further up the list of paths having precedence over the macros further down the path.

For example, given the search paths ‘foo’ and ‘bar’, foo/macros.pt could define ‘users’ and ‘page’, while bar/macros.pt could define ‘users’ and ‘site’. In the lookup this would result in ‘users’ and ‘page’ being loaded loaded from foo and ‘site’ being loaded from bar.

lookup[source]
__getitem__(name: str) chameleon.zpt.template.Macro[source]
core.templates.get_template_loader(template_directories: list[str], settings: dict[str, Any]) TemplateLoader[source]

Returns the Chameleon template loader for templates with the extension .pt.

core.templates.get_chameleon_render(loader: TemplateLoader, name: str, original_render: Callable[[str, CoreRequest], _T]) Callable[[dict[str, Any], CoreRequest], _T][source]

Returns the Chameleon template renderer for the required template.

core.templates.render_template(template: str, request: core.request.CoreRequest, content: dict[str, Any], suppress_global_variables: bool | Literal['infer'] = 'infer') markupsafe.Markup[source]

Renders the given template. Use this if you need to get the rendered value directly. If oyu render a view, this is not needed!

By default, mail templates (templates strting with ‘mail_’) skip the inclusion of global variables defined through the template_variables directive.

core.templates.render_macro(macro: chameleon.zpt.template.Macro, request: core.request.CoreRequest, content: dict[str, Any], suppress_global_variables: bool = True) markupsafe.Markup[source]

Renders a chameleon.zpt.template.Macro like this:

layout.render_macro(layout.macros['my_macro'], **vars)

This code is basically a stripped down version of this: https://github.com/malthe/chameleon/blob/257c9192fea4b158215ecc4f84e1249d4b088753/src/chameleon/zpt/template.py#L206.

As such it doesn’t treat chameleon like a black box and it will probably fail one day in the future, if Chameleon is refactored. Our tests will detect that though.