From 3cd04c3dbca36f5f0905fff2d0e8da71d77cf233 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20Lov=C3=A9n?= Date: Wed, 12 Dec 2018 23:31:18 +0100 Subject: [PATCH] Allow more templates in a string --- README.md | 5 ++--- card-tools.js | 28 +++++++++++++++------------- 2 files changed, 17 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 43f8197..fc64e9d 100644 --- a/README.md +++ b/README.md @@ -186,7 +186,7 @@ This lets you parse a user specified template like `[[ light.bed_light.state ]]` Two things are important: -- The template must start with `[[` and end with `]]` +- Template must start with `[[` and end with `]]` - This is not in any way the same kind of template as used in the Home Assistant configuration The templates are parsed by reading one step at a time from the `hass.states` object. @@ -199,5 +199,4 @@ Next is one of: - `last_changed` - `last_updated` -If the string does not match the template format, the original string is returned. -Otherwise the requested value is returned, or an error message on failure. +The function replaces any template found in the supplied string with the requested value, or an error message on failure. diff --git a/card-tools.js b/card-tools.js index d3b40f2..d5205e7 100644 --- a/card-tools.js +++ b/card-tools.js @@ -178,20 +178,22 @@ if (!window.cardTools){ }; cardTools.parseTemplate = - (str) => { - if(!str || !str.startsWith('[[ ') || !str.endsWith(' ]]')) - return str; - try { - str = str.replace(/^\[\[\s+|\s+\]\]$/g, '') - const parts = str.split("."); - let v = cardTools.hass.states[`${parts[0]}.${parts[1]}`]; - parts.shift(); - parts.shift(); - parts.forEach(item => v = v[item]); - return v; - } catch { - return `[[ Template matching failed ${str} ]]`; + (text, error) => { + const _parse = (str) => { + try { + str = str.replace(/^\[\[\s+|\s+\]\]$/g, '') + const parts = str.split("."); + let v = cardTools.hass.states[`${parts[0]}.${parts[1]}`]; + parts.shift(); + parts.shift(); + parts.forEach(item => v = v[item]); + return v; + } catch { + return error || `[[ Template matching failed ${str} ]]`; + } } + text = text.replace(/(\[\[\s.*?\s\]\])/g, (str, p1, offset, s) => _parse(str)); + return text; } window.cardTools = cardTools;