core.templates
==============
.. py:module:: core.templates
.. autoapi-nested-parse::
Integrates the Chameleon template language.
This is basically a copy of more.chameleon, with the additional inclusion of a
gettext translation function defined by :mod:`onegov.core.i18n`.
To use a chameleon template, applications have to specify the templates
directory, in addition to inheriting from
:class:`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
----------
.. autoapisummary::
core.templates._T
core.templates.AUTO_RELOAD
core.templates.BOOLEAN_HTML_ATTRS
Classes
-------
.. autoapisummary::
core.templates.PageTemplate
core.templates.PageTemplateFile
core.templates.TemplateLoader
core.templates.MacrosLookup
Functions
---------
.. autoapisummary::
core.templates.get_default_vars
core.templates.get_template_loader
core.templates.get_chameleon_render
core.templates.render_template
core.templates.render_macro
Module Contents
---------------
.. py:data:: _T
.. py:data:: AUTO_RELOAD
.. py:data:: BOOLEAN_HTML_ATTRS
.. py:class:: PageTemplate(*args: Any, **kwargs: Any)
Bases: :py:obj:`chameleon.PageTemplate`
Constructor for the page template language.
Takes a string input as the only positional argument::
template = PageTemplate("
Hello, ${name}.
")
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:
``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``.
.. py:class:: PageTemplateFile(*args: Any, **kwargs: Any)
Bases: :py:obj:`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.
.. py:function:: get_default_vars(request: core.request.CoreRequest, content: collections.abc.Mapping[str, Any], suppress_global_variables: bool = False) -> dict[str, Any]
.. py:class:: TemplateLoader(search_path: collections.abc.Sequence[str] | str | None = None, default_extension: str | None = None, *, formats: _FormatsMapping | None = None, **kwargs: Any)
Bases: :py:obj:`chameleon.PageTemplateLoader`
Extends the default page template loader with the ability to
lookup macros in various folders.
.. py:attribute:: formats
.. py:property:: macros
:type: MacrosLookup
.. py:property:: mail_macros
:type: MacrosLookup
.. py:class:: MacrosLookup(search_paths: collections.abc.Iterable[_typeshed.StrPath], name: str = 'macros.pt')
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.
.. py:attribute:: lookup
.. py:method:: __getitem__(name: str) -> chameleon.zpt.template.Macro
.. py:function:: get_template_loader(template_directories: list[str], settings: dict[str, Any]) -> TemplateLoader
Returns the Chameleon template loader for templates with the extension
``.pt``.
.. py:function:: get_chameleon_render(loader: TemplateLoader, name: str, original_render: collections.abc.Callable[[str, core.request.CoreRequest], _T]) -> collections.abc.Callable[[dict[str, Any], core.request.CoreRequest], _T]
Returns the Chameleon template renderer for the required template.
.. py:function:: render_template(template: str, request: core.request.CoreRequest, content: dict[str, Any], suppress_global_variables: bool | Literal['infer'] = 'infer') -> markupsafe.Markup
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.
.. py:function:: render_macro(macro: chameleon.zpt.template.Macro, request: core.request.CoreRequest, content: dict[str, Any], suppress_global_variables: bool = True) -> markupsafe.Markup
Renders a :class:`chameleon.zpt.template.Macro` like this::
layout.render_macro(layout.macros['my_macro'], **vars)
This code is basically a stripped down version of this:
``_.
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.