diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index c6096e11aab..adbb8fe0d36 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -13,7 +13,7 @@ from functools import cache, lru_cache, partial, wraps import json import logging import math -from operator import attrgetter +from operator import attrgetter, contains import random import re import statistics @@ -2085,6 +2085,7 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment): self.filters["iif"] = iif self.filters["bool"] = forgiving_boolean self.filters["version"] = version + self.filters["contains"] = contains self.globals["log"] = logarithm self.globals["sin"] = sine self.globals["cos"] = cosine @@ -2121,6 +2122,7 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment): self.tests["is_number"] = is_number self.tests["match"] = regex_match self.tests["search"] = regex_search + self.tests["contains"] = contains if hass is None: return diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index c080b5b684c..cb5445516e5 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -4070,3 +4070,33 @@ async def test_template_states_can_serialize(hass: HomeAssistant) -> None: template_state = template.TemplateState(hass, state, True) assert template_state.as_dict() is template_state.as_dict() assert json_dumps(template_state) == json_dumps(template_state) + + +@pytest.mark.parametrize( + "seq, value, expected", + [ + ([0], 0, True), + ([1], 0, False), + ([False], 0, True), + ([True], 0, False), + ([0], [0], False), + (["toto", 1], "toto", True), + (["toto", 1], "tata", False), + ([], 0, False), + ([], None, False), + ], +) +def test_contains(hass, seq, value, expected): + """Test contains.""" + assert ( + template.Template("{{ seq | contains(value) }}", hass).async_render( + {"seq": seq, "value": value} + ) + == expected + ) + assert ( + template.Template("{{ seq is contains(value) }}", hass).async_render( + {"seq": seq, "value": value} + ) + == expected + )