Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add jinja is list filter #201

Merged
merged 4 commits into from
Oct 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading