From 1878c92c915a242baa39e1a72f20916e0e8fbfce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Lov=C3=A9n?= Date: Fri, 15 Nov 2019 22:16:18 +0100 Subject: [PATCH] Add global variables from integration configuration. Thanks, Dwains. --- README.md | 28 ++++++++++++++++++++++ custom_components/lovelace_gen/__init__.py | 7 ++++-- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f08caee..9270ec8 100644 --- a/README.md +++ b/README.md @@ -252,6 +252,34 @@ elements: # FAQ +### How can I do global variables? +You can add variables to the `lovelace_gen` configuration in `configuration.yaml` and then refernce them in lovelace using `{{ _global }}`. + +E.g.: +```yaml +lovelace_gen: + rooms: + - living_room + - kitchen + - bed_room +``` + +```yaml +type: entities +entities: + {% for room in _global.rooms %} + - type: custom:auto-entities + card: + type: custom:fold-entity-row + head: + type: section + label: {{ room|capitalize }} + filter: + include: + - area: {{ room }} + {% endfor %} +``` + ### Can I use this for my general Home Assistant configuration? It's called **lovelace**\_gen for a reason... That being said - it *might* work. Or it might not. There's really no way to diff --git a/custom_components/lovelace_gen/__init__.py b/custom_components/lovelace_gen/__init__.py index 885ea48..94edcb2 100644 --- a/custom_components/lovelace_gen/__init__.py +++ b/custom_components/lovelace_gen/__init__.py @@ -14,6 +14,8 @@ _LOGGER = logging.getLogger(__name__) jinja = jinja2.Environment(loader=jinja2.FileSystemLoader("/")) +llgen_config = {} + def load_yaml(fname, args={}): try: ll_gen = False @@ -22,7 +24,7 @@ def load_yaml(fname, args={}): ll_gen = True if ll_gen: - stream = io.StringIO(jinja.get_template(fname).render(args)) + stream = io.StringIO(jinja.get_template(fname).render({**args, "_global": llgen_config})) stream.name = fname return loader.yaml.load(stream, Loader=loader.SafeLineLoader) or OrderedDict() else: @@ -60,5 +62,6 @@ loader.load_yaml = load_yaml loader.yaml.SafeLoader.add_constructor("!include", _include_yaml) loader.yaml.SafeLoader.add_constructor("!file", _uncache_file) -async def async_setup(*_): +async def async_setup(hass, config): + llgen_config.update(config.get("lovelace_gen")); return True