Variables and templating

Documents can contain template strings that are parsed using Minijinja.

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.internal_get('map')['key'])  # See the "Accessing Data" section
{{ map.key2 }} <- all references are made from the root of the document

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

>>> document.freeze()
>>> 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:
      $name: 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.

Iterating

Configcrunch supports iteration over lists and over dicts (use .keys(),``.values()`` or .items() depending on what you need to iterate over).

Value type interpretation

Configcrunch keeps the types of values as they are in the documents. The only expectation to this is values that contain only variables and are parse-able as an integer. These are auto-converted to integers for convenience. If you don’t want that and need to interpret them as strings instead, use the str filter as described below.

Filters

Minijinja supports filters, which are explained in more detail in the Minijinja documentation.

All built-in filters can be used. In addition the following filters exist:

  • str ({{ var|str }}):

    (Only works if the template contains ONLY this one statement and nothing else!) Forces the value to be interpreted as a string, even if it could be auto-converted to an integer.

  • substr_start ({{ var|substr_start(X) }}):

    Returns the first X characters of the string var.

  • startswith ({{ var|startswith(string) }}):

    Returns true if the string var starts with string, else false.