From 14fd72317668f4596e9af2a041c29302566e2101 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Lov=C3=A9n?= Date: Thu, 16 Jan 2020 12:30:51 +0100 Subject: [PATCH] Add fromjson filter --- README.md | 12 ++++++++++++ custom_components/lovelace_gen/__init__.py | 7 ++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e0f71a1..bc91fef 100644 --- a/README.md +++ b/README.md @@ -150,6 +150,18 @@ name: {{ name }} Be careful about the syntax here. Note that the arguments are given as a list and is indented under the `!include` statement. The second item in the list is a dictionary. +> Note: If you want to pass a dictionary of values into a file, you need to convert it to json first: +> ```yaml +> {% set mydict = {"a": 1, "b": 2} %} +> variable: {{ mydict | tojson }} +> ``` +> And then convert it back from json inside the file: +> ```yaml +> content: The value of a is {{ (variable | fromjson)['a'] }} +> ``` +> +> The `fromjson` filter is a feature of `lovelace_gen` and not normally included in jinja. + ## Invalidate cache of files If you use lots of custom lovelace cards, chances are that you have run into caching problems at one point or another. diff --git a/custom_components/lovelace_gen/__init__.py b/custom_components/lovelace_gen/__init__.py index 6bcc742..c1e0974 100644 --- a/custom_components/lovelace_gen/__init__.py +++ b/custom_components/lovelace_gen/__init__.py @@ -12,8 +12,13 @@ _LOGGER = logging.getLogger(__name__) +def fromjson(value): + return json.loads(value) + jinja = jinja2.Environment(loader=jinja2.FileSystemLoader("/")) +jinja.filters['fromjson'] = fromjson + llgen_config = {} def load_yaml(fname, args={}): @@ -89,4 +94,4 @@ def compose_node(self, parent, index): self.ascend_resolver() return node -yaml.composer.Composer.compose_node = compose_node \ No newline at end of file +yaml.composer.Composer.compose_node = compose_node