Variables and templating

Documents can contain template strings based on Jinja2. Only basic referencing of variables and calling of functions is supported, although in theory most of Jinja2 can be used.

Variables are bound to documents. To use documents, include them in template strings:

example:
  this: "{{ int }} is a number"
  int: 12
  map:
    key: "{{ map.key2 }} <- all references are made from the root of the document"
    key2: value 2

To process variables, call process_vars().

>>> document = Example.from_yaml("fixtures/variables.yml")
>>> print(document['map']['key'])
{{ map.key2 }} <- all references are made from the root of the document

>>> document.process_vars()
Example(...)

>>> print(document['this'])
12 is a number
>>> print(document['map']['key2'])
value 2
>>> print(document['map']['key'])
value 2 <- all references are made from the root of the document

You can also use variables with merged documents and sub-documents, but make sure to call resolve_and_merge_references() before process_vars()!

Sub-documents can reference values in parent documents by using the parent() variable helper function. Variable helpers are further explained in the following chapter.

parent:
  name: hello
  direct:
    this: '{{ parent().name }} {{ parent().map.key.this }}'
  map:
    key:
      this: world
>>> document = Parent.from_yaml("fixtures/variables_parent.yml")
>>> document.resolve_and_merge_references([])
Parent(...)
>>> document.process_vars()
Parent(...)

This will result in the following document:

parent:
  name: hello
  direct:
    this: hello world
  map:
    key:
      this: world

Warning

It IS supported to reference fields in templates that contain other templates.

BUT it is NOT supported to reference fields with template strings when using the parent() helper in any way.