vinegar.template.jinja
Support for Jinja templates (using the Jinja 2 library).
The JinjaEngine provided by this module use the Jinja 2 library for rendering
template files. The Jinja 2 Environment can be configured when
creating the template engine.
The preferred way of creating an instance of the Jinja template engine is by
calling the get_instance function, not by creating an instance of
JinjaEngine directly.
Template syntax
The Jinja template engine supports the full range of features provided by the Jinja 2 library. Please refer to the Jinja 2 documentation to learn more about how to write Jinja templates.
Unless disabled by setting provide_transform_functions to False, this
template engine provides a transform object that can be used to access
functions from the vinegar.transform package.
Optionally, access to selected Python modules can be enabled through the
provide_python_modules setting. If this setting is non-empty, a object
with the name python is added to the template context. This object can then
be used to access the explicitly allowed Python modules.
This template engine also provides a raise function that can be used to
raise a TemplateError from within templates. That function is added to the
globals so that it is also available in templates that are imported without the
context.
The environment created by this template engine adds four extensions by default:
jinja2.ext.do: This extension provides thedotag that can be used to execute some code (similar to a{{ ... }}block) without generating output.jinja2.ext.loopcontrols: This extension provides thebreakandcontinuetags that can be used for loop control.jinja2.ext.with_: This extension provides thewithtag. Since Jinja 2.10 this tag is available even when this extension is not loaded.vinegar.template.jinja.SerializerExtension: This extension provides tags and filters for dealing with JSON and YAML. Please refer to the class documentation for details.
Please note that these extensions are not available when explicitly setting the
environment’s extensions option through the env configuration option.
In this case, each extension that is desired has to be mentioned explicitly.
Configuration options
The template engine provded by this module supports the following configuration
options that can be passed through the config dictionary that is passed to
get_instance:
cache_enabled:This option (a
bool) specifies whether caching is enabled. IfTrue(the default), templates are only recompiled when the corresponding file has been modified. Modification is detected by comparing the file’sctimeandmtime. IfFalsethe template is recompiled on each request. This can make sense if files are changed rapidly and the time stamps provided by the file system do not provide sufficient precision. This option is actually handled by the loader, so it will have no effect when supplying a custom loader through theloaderenvironment option.context:This options (a
dict) provides extra objects that are made available in the template’s context. These objects are provided in addition to the objects passed through thecontextparameter of therendermethod. In case of a key collision, objects specified via this option take precedence over objects parsed torender.env:This option is used to specify a dict that is used when creating the
Environment. By default three options are passed to the environment, unless they are explicitly specified in theenvdict:autoescapeis set toFalseandkeep_trailing_newlineis set toTrue. Theloaderis also created automatically based on theroot_dirconfiguration option.provide_python_modules:This option (
None, astr, or a sequence ofstr) specifies which Python module should be made available through thepythonobject that is added to the context. IfNoneor empty (the default), thepythonobject is not added to the context at all. Each of the strings can either be a module name, a wildcard match all sub-modules (e.g.parent_module.*), or the global wildcard*, which matches all module names. In a template, the attributes of a module that has been allowed through this option can be accessed by specifying the combination of the module name and the attribute name as an index to thepythonobject. For example, if access to theosmodule is allowed, the following expression can be used in a template:python["os.stat"]("/path/to/file")provide_transform_functions:This option (a
bool) specifies whether an object with the nametransformis added to the context. IfTrue(the default), thetransformobject allows easy access to the transformation functions provided byvinegar.transform. Thetransformobject is added to the globals. This means that it is also going to be available in imported templates that are not imported with the context. Ifprovide_transform_functionsisFalse, thetransformobject is not available from templates. Thetransformobject can be used like in the following example:transform['string.to_upper']('This is all converted to upper case.')relative_includes:This option (a
bool) specifies whether included templates (these are templates that are use by another template through theimportorincludedirectives) are resolved relative to the using template or relative to the root of the loader. The default value of this option isTrue, meaning that included templates are resolved relative to their parent.root_dir:This option (a
str) specifies the root directory for the loader that loads templates. If it isNone(the default), template names that represent an absolute path on the file system are used as-is and other template names are resolved relative to the current working directory. Please note that this option is only effective if not custom loader is specified through theenvoption. It is an error to specify this option when also specifying a custom loader.
- class vinegar.template.jinja.JinjaEngine(config: Mapping[Any, Any])
Template engine using the Jinja 2 library.
For information about the configuration options supported by this template engine, please refer to the
module documentation.- render(template_path: str, context: Mapping[str, Any]) str
Render the template file specified by
template_pathand return the result.- Parameters:
template_path – path to the template file.
- Param:
context: context available to the template. The objects supplied by this mapping should be made available to the template code when rendering. The details of how the context objects are made available depends on the template engine.
- Returns:
result of rendering the template.
- class vinegar.template.jinja.SerializerExtension(environment: Environment)
Jinja extension for dealing with JSON and YAML.
This extension adds four filters and four tags to Jinja. The four filters are:
load_json(parses a JSON string into the corresponding object)load_yaml(parses a YAML string into the corresponding object)json(serializes an object into JSON)yaml(serializes an object into YAML)
The
jsonfilter has two optional arguments:json(sort_keys=False, indent=None)
The
sort_keysoption defines whether keys are in dictionaries are sorted when serializing the dictionaries. If it is not set, the keys are serialized in iteration order.The
indentoption defines the number of spaces to use for indentation when formatting the output. IfNone, the output is rendered without line breaks and thus without indentation.The
yamlfilter has one optional argument:yaml(flow_style=True)
If the
flow_styleargument isTrue, the serialization uses the flow style, if it the argument isFalseit uses the block style. Using the block style is problematic when the serialization result is supposed to be embedded into another document (because the indentation will typically not match the one of the surrounding document).The
load_jsonandload_yamlfilters do not have any arguments.The four tags provided by this extension are:
import_jsonimport_yamlload_jsonload_yaml
Example for
import_json:This renders the template
json.jinja, parses it as JSON, and puts it intovalue. Essentially, it is a shorthand notation for:The
import_yamltag works exactly like theimport_jsontag, with the exception that it parses YAML instead of JSON:Example for
load_json:The
load_jsontag takes everything up to theendloadtag and parses it as JSON. Essentially, it is a shorthand notation for:or (in Jinja 2.10 and newer)
The
load_yamltag can be used in the same way as theload_jsontag with the only exception being that it expects YAML content.- parse(parser: Parser) Node | List[Node]
If any of the
tagsmatched this method is called with the parser as first argument. The token the parser stream is pointing at is the name token that matched. This method has to return one or a list of multiple nodes.
- tags: Set[str] = {'import_json', 'import_yaml', 'load_json', 'load_yaml'}
if this extension parses this is the list of tags it’s listening to.
- vinegar.template.jinja.get_instance(config: Mapping[Any, Any]) JinjaEngine
Create a Jinja template engine.
For information about the configuration options supported by that engine, please refer to the
module documentation.- Parameters:
config – configuration for the template engine.
- Returns:
Jinja template engine using the specified configuration.