From 865ea82432d27c2b2d5ef187717a1bbff5b46b9f Mon Sep 17 00:00:00 2001 From: Neil Crosby Date: Tue, 30 Oct 2018 18:13:20 +0000 Subject: [PATCH] Allow jinja namespace command to work. (#18011) --- homeassistant/helpers/template.py | 6 ++++++ tests/helpers/test_template.py | 17 +++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index 83fe36d35c5..66f289724be 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -9,6 +9,7 @@ import re import jinja2 from jinja2 import contextfilter from jinja2.sandbox import ImmutableSandboxedEnvironment +from jinja2.utils import Namespace from homeassistant.const import ( ATTR_LATITUDE, ATTR_LONGITUDE, ATTR_UNIT_OF_MEASUREMENT, MATCH_ALL, @@ -618,6 +619,11 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment): """Test if callback is safe.""" return isinstance(obj, AllStates) or super().is_safe_callable(obj) + def is_safe_attribute(self, obj, attr, value): + """Test if attribute is safe.""" + return isinstance(obj, Namespace) or \ + super().is_safe_attribute(obj, attr, value) + ENV = TemplateEnvironment() ENV.filters['round'] = forgiving_round diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 3f32f444aaf..573a9f78b72 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -963,6 +963,23 @@ class TestHelpersTemplate(unittest.TestCase): "{{ is_state('media_player.' ~ where , 'playing') }}", {'where': 'livingroom'}) + def test_jinja_namespace(self): + """Test Jinja's namespace command can be used.""" + test_template = template.Template( + ( + "{% set ns = namespace(a_key='') %}" + "{% set ns.a_key = states.sensor.dummy.state %}" + "{{ ns.a_key }}" + ), + self.hass + ) + + self.hass.states.set('sensor.dummy', 'a value') + assert 'a value' == test_template.render() + + self.hass.states.set('sensor.dummy', 'another value') + assert 'another value' == test_template.render() + @asyncio.coroutine def test_state_with_unit(hass):