Add the "traverse" jinja filter

which can be really useful in states to select some leaf pillar data or
fallback with a default value.
This commit is contained in:
Bruno Binet 2018-07-19 17:59:30 +02:00
parent e828167114
commit 37a41226d5
2 changed files with 35 additions and 0 deletions

View File

@ -1148,6 +1148,40 @@ Returns:
}'
}
.. jinja_ref:: traverse
``traverse``
--------------
.. versionadded:: 2018.3.3
Traverse a dict or list using a colon-delimited target string.
The target 'foo:bar:0' will return data['foo']['bar'][0] if this value exists,
and will otherwise return the provided default value.
Example:
.. code-block:: jinja
{{ {'a1': {'b1': {'c1': 'foo'}}, 'a2': 'bar'} | traverse('a1:b1', 'default') }}
Returns:
.. code-block:: python
{'c1': 'foo'}
.. code-block:: jinja
{{ {'a1': {'b1': {'c1': 'foo'}}, 'a2': 'bar'} | traverse('a2:b2', 'default') }}
Returns:
.. code-block:: python
'default'
.. _`builtin filters`: http://jinja.pocoo.org/docs/templates/#builtin-filters
.. _`timelib`: https://github.com/pediapress/timelib/

View File

@ -460,6 +460,7 @@ def traverse_dict(data, key, default=None, delimiter=DEFAULT_TARGET_DELIM):
return data
@jinja_filter('traverse')
def traverse_dict_and_list(data, key, default=None, delimiter=DEFAULT_TARGET_DELIM):
'''
Traverse a dict or list using a colon-delimited (or otherwise delimited,