Skip to main content

Application specific YAML tag of Jinja2 template

Project description

jinjyaml

GitHub tag Test Python Package Documentation Status Quality Gate Status PyPI

Application specific tag of Jinja2 template in PyYAML.

It may be useful if you only want to render special tag nodes in the document, instead of whole YAML string as a template.

Usage

Example 1

>>> import yaml
>>> import jinjyaml as jy
>>>
>>> ctor = jy.Constructor()
>>> yaml.add_constructor('!j2', ctor, yaml.FullLoader)
>>>
>>> s = '''
... array:
...   !j2 |
...     {% for i in range(n) %}
...     - sub{{i}}: {{loop.index}}
...     {% endfor %}
... '''
>>>
>>> obj = yaml.full_load(s)
>>>
>>> data = jy.extract(obj, context={'n': 3})
>>> print(data)
{'array': [{'sub0': 1}, {'sub1': 2}, {'sub2': 3}]}

Example 2

We have such YAML files:

  • child-1.yml:

    "1.1": one
    "1.2": two
    
  • child-2.yml:

    "2.1":
      "2.1.1": three
      "2.1.2": four
    
  • main.yml:

    children: !j2 |
    
      {% include "child-1.yml" %}
      {% include "child-2.yml" %}
    

execute python code:

from pprint import pprint

import jinja2
import jinjyaml as jy
import yaml

env = jinja2.Environment(loader=jinja2.FileSystemLoader('.'))

ctor = jy.Constructor()
yaml.add_constructor('!j2', ctor, yaml.FullLoader)

with open('main.yml') as fp:
    doc = yaml.full_load(fp)

obj = jy.extract(doc, env)
pprint(obj)

We'll get:

{'foo': {'1.1': 'one',
         '1.2': 'two',
         '2.1': {'2.1.1': 'three', '2.1.2': 'four'}}}

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

jinjyaml-0.3.tar.gz (6.4 kB view hashes)

Uploaded Source

Built Distribution

jinjyaml-0.3-py3-none-any.whl (7.5 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page