ruamel.yaml.jinja2
ruamel.yaml.jinja2 is a plugin for ruamel.yaml that enables pre- and post-processing of Jinja2 templates within YAML files. This allows YAML files containing Jinja2 constructs to be loaded, modified as YAML, and then dumped back while preserving the Jinja2 templating. The current version is 0.2.7, released in September 2021, indicating a slow release cadence or maintenance mode.
Warnings
- breaking Using different `YAML(typ='jinja2')` instances for loading and dumping will result in an `AttributeError` because the instance used for loading stores crucial internal information required for the subsequent dumping process.
- gotcha Certain complex Jinja2 constructs, especially those that result in invalid YAML when not rendered (e.g., `{{- with ... }}` on a line of its own, or undocumented `jinja2` constructs), may not be handled correctly by `ruamel.yaml.jinja2` and might require manual pre-processing or lead to unexpected parsing errors.
- gotcha The installation command `pip install ruamel.yaml[jinja2]` is the recommended way to ensure `ruamel.yaml.jinja2` is correctly integrated with `ruamel.yaml`. Direct installation of `ruamel-yaml-jinja2` might not set up the necessary plugin mechanism correctly, leading to unexpected behavior or an inability to use `typ='jinja2'`.
- deprecated The `ruamel.yaml` project, which `ruamel.yaml.jinja2` extends, has discussed potential breaking changes regarding its PyPI package name to comply with PEP 625 (possibly changing to `ruamel_yaml`). While this specific plugin is not directly affected by a name change, its core dependency might experience installation or import path changes in the future, although `ruamel.yaml` has indicated they are trying to avoid this for older versions.
Install
-
pip install 'ruamel.yaml[jinja2]' -
pip install ruamel-yaml-jinja2
Imports
- YAML
from ruamel.yaml import YAML
Quickstart
import sys
from ruamel.yaml import YAML
yaml_str = """
- {{ name }}: "{% include 'ethnicity.jinja2' with context %}"
age: 43
hobbies: {% include 'hobbies.jinja2' with context %}
"""
yaml = YAML(typ='jinja2')
yaml.preserve_quotes = True
data = yaml.load(yaml_str)
data[0]['age'] = 18
yaml.dump(data, sys.stdout)