diff --git a/.changes/unreleased/Under the Hood-20241001-161733.yaml b/.changes/unreleased/Under the Hood-20241001-161733.yaml new file mode 100644 index 0000000..9ef3baa --- /dev/null +++ b/.changes/unreleased/Under the Hood-20241001-161733.yaml @@ -0,0 +1,6 @@ +kind: Under the Hood +body: Add a jinja "is_list" filter +time: 2024-10-01T16:17:33.652809-04:00 +custom: + Author: gshank + Issue: "200" diff --git a/dbt_common/clients/jinja.py b/dbt_common/clients/jinja.py index d27c264..2cee922 100644 --- a/dbt_common/clients/jinja.py +++ b/dbt_common/clients/jinja.py @@ -470,11 +470,16 @@ def __reduce__(self) -> NoReturn: return Undefined +def is_list(value): + return isinstance(value, list) + + NATIVE_FILTERS: Dict[str, Callable[[Any], Any]] = { "as_text": TextMarker, "as_bool": BoolMarker, "as_native": NativeMarker, "as_number": NumberMarker, + "is_list": is_list, } @@ -483,6 +488,7 @@ def __reduce__(self) -> NoReturn: "as_bool": lambda x: x, "as_native": lambda x: x, "as_number": lambda x: x, + "is_list": is_list, } diff --git a/tests/unit/test_jinja.py b/tests/unit/test_jinja.py index cf44eee..e839296 100644 --- a/tests/unit/test_jinja.py +++ b/tests/unit/test_jinja.py @@ -1,7 +1,7 @@ import unittest from dbt_common.clients._jinja_blocks import BlockTag -from dbt_common.clients.jinja import extract_toplevel_blocks +from dbt_common.clients.jinja import extract_toplevel_blocks, get_template, render_template from dbt_common.exceptions import CompilationError @@ -503,3 +503,24 @@ def test_if_endfor_newlines(self) -> None: hi {% endmaterialization %} """ + + +def test_if_list_filter(): + jinja_string = """ + {%- if my_var | is_list -%} + Found a list + {%- else -%} + Did not find a list + {%- endif -%} + """ + # Check with list variable + ctx = {"my_var": ["one", "two"]} + template = get_template(jinja_string, ctx) + rendered = render_template(template, ctx) + assert "Found a list" in rendered + + # Check with non-list variable + ctx = {"my_var": "one"} + template = get_template(jinja_string, ctx) + rendered = render_template(template, ctx) + assert "Did not find a list" in rendered