Allow more templates in a string

This commit is contained in:
Thomas Lovén 2018-12-12 23:31:18 +01:00
parent 523255ba17
commit 3cd04c3dbc
2 changed files with 17 additions and 16 deletions

View File

@ -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 `[[<space>` and end with `<space>]]`
- Template must start with `[[<space>` and end with `<space>]]`
- 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.

View File

@ -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;