diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index bdef5541983..d5dbcb77a32 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -187,6 +187,10 @@ class AllStates(object): sorted(self._hass.states.async_all(), key=lambda state: state.entity_id)) + def __len__(self): + """Return number of states.""" + return len(self._hass.states.async_entity_ids()) + def __call__(self, entity_id): """Return the states.""" state = self._hass.states.get(entity_id) @@ -213,6 +217,10 @@ class DomainStates(object): if state.domain == self._domain), key=lambda state: state.entity_id)) + def __len__(self): + """Return number of states.""" + return len(self._hass.states.async_entity_ids(self._domain)) + class TemplateState(State): """Class to represent a state object in a template.""" diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 6a2a77f5c71..e668bd5b6cd 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -782,3 +782,17 @@ def test_state_with_unit(hass): hass) assert tpl.async_render() == '' + + +@asyncio.coroutine +def test_length_of_states(hass): + """Test fetching the length of states.""" + hass.states.async_set('sensor.test', '23') + hass.states.async_set('sensor.test2', 'wow') + hass.states.async_set('climate.test2', 'cooling') + + tpl = template.Template('{{ states | length }}', hass) + assert tpl.async_render() == '3' + + tpl = template.Template('{{ states.sensor | length }}', hass) + assert tpl.async_render() == '2'