Skip to content

Commit

Permalink
Add jinja is list filter (#201)
Browse files Browse the repository at this point in the history
* Add is_list jinja filter

* Changie

* Add test
  • Loading branch information
gshank authored Oct 1, 2024
1 parent 60ffb06 commit 8f2b1d5
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
6 changes: 6 additions & 0 deletions .changes/unreleased/Under the Hood-20241001-161733.yaml
Original file line number Diff line number Diff line change
@@ -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"
6 changes: 6 additions & 0 deletions dbt_common/clients/jinja.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}


Expand All @@ -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,
}


Expand Down
23 changes: 22 additions & 1 deletion tests/unit/test_jinja.py
Original file line number Diff line number Diff line change
@@ -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


Expand Down Expand Up @@ -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

0 comments on commit 8f2b1d5

Please sign in to comment.