I'm trying to load a yaml file in jinja2 format and "evaluate"/"render" the template. Here, the example:
{% set name = "pyexcel-ezodf" %}
{% set version = "0.3.3" %}
package:
name: {{ name|lower }}
version: {{ version }}
I would like to be able to load the yaml file and said yaml['package']['version']=0.3.3
I have to try ruamel YAML but it doesn't evaluate the version only give me a package.
here the python code:
yaml = YAML(typ='jinja2')
yaml.allow_duplicate_keys = True
yaml.explicit_start = True
yaml_content = yaml.load(content)
print (yaml_content['package'])
Loading jinja2 templates for YAML with the typ='jinja2'
parameter passed to ruamel.yaml
' YAML()
instance is there in order to make valid YAML out of the template, so you can then modify the template as if it were valid YAML and write it back. It doesn't do any template rendering and doesn't claim to do so anywhere in the documentation.
What you need to do is first render the template using jinja2 and then load the value (for which you can use the fast yaml = YAML(typ='safe')
option.
You can e.g. do something like:
from jinja2 import Environment
from ruamel.yaml import YAML
yaml = YAML(typ='safe')
yaml_content = yaml.load(Environment().from_string(content).render())
print(yaml_content['package'])