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 the do tag that can be used to execute some code (similar to a {{ ... }} block) without generating output.

  • jinja2.ext.loopcontrols: This extension provides the break and continue tags that can be used for loop control.

  • jinja2.ext.with_: This extension provides the with tag. 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. If True (the default), templates are only recompiled when the corresponding file has been modified. Modification is detected by comparing the file’s ctime and mtime. If False the 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 the loader environment 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 the context parameter of the render method. In case of a key collision, objects specified via this option take precedence over objects parsed to render.

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 the env dict: autoescape is set to False and keep_trailing_newline is set to True. The loader is also created automatically based on the root_dir configuration option.

provide_python_modules:

This option (None, a str, or a sequence of str) specifies which Python module should be made available through the python object that is added to the context. If None or empty (the default), the python object 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 the python object. For example, if access to the os module 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 name transform is added to the context. If True (the default), the transform object allows easy access to the transformation functions provided by vinegar.transform. The transform object 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. If provide_transform_functions is False, the transform object is not available from templates. The transform object 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 the import or include directives) are resolved relative to the using template or relative to the root of the loader. The default value of this option is True, 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 is None (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 the env option. 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_path and 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 json filter has two optional arguments:

json(sort_keys=False, indent=None)

The sort_keys option 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 indent option defines the number of spaces to use for indentation when formatting the output. If None, the output is rendered without line breaks and thus without indentation.

The yaml filter has one optional argument:

yaml(flow_style=True)

If the flow_style argument is True, the serialization uses the flow style, if it the argument is False it 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_json and load_yaml filters do not have any arguments.

The four tags provided by this extension are:

  • import_json

  • import_yaml

  • load_json

  • load_yaml

Example for import_json:

This renders the template json.jinja, parses it as JSON, and puts it into value. Essentially, it is a shorthand notation for:

The import_yaml tag works exactly like the import_json tag, with the exception that it parses YAML instead of JSON:

Example for load_json:

The load_json tag takes everything up to the endload tag and parses it as JSON. Essentially, it is a shorthand notation for:

or (in Jinja 2.10 and newer)

The load_yaml tag can be used in the same way as the load_json tag with the only exception being that it expects YAML content.

parse(parser: Parser) Node | List[Node]

If any of the tags matched 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.