From 37a41226d5b1486ad915fc67f54ee702bf1d4520 Mon Sep 17 00:00:00 2001 From: Bruno Binet Date: Thu, 19 Jul 2018 17:59:30 +0200 Subject: [PATCH] Add the "traverse" jinja filter which can be really useful in states to select some leaf pillar data or fallback with a default value. --- doc/topics/jinja/index.rst | 34 ++++++++++++++++++++++++++++++++++ salt/utils/data.py | 1 + 2 files changed, 35 insertions(+) diff --git a/doc/topics/jinja/index.rst b/doc/topics/jinja/index.rst index 8d580f771d..9e21399183 100644 --- a/doc/topics/jinja/index.rst +++ b/doc/topics/jinja/index.rst @@ -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/ diff --git a/salt/utils/data.py b/salt/utils/data.py index cd10a85186..3f95b4887d 100644 --- a/salt/utils/data.py +++ b/salt/utils/data.py @@ -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,