Allow more templates in a string
This commit is contained in:
parent
523255ba17
commit
3cd04c3dbc
@ -186,7 +186,7 @@ This lets you parse a user specified template like `[[ light.bed_light.state ]]`
|
|||||||
|
|
||||||
Two things are important:
|
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
|
- 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.
|
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_changed`
|
||||||
- `last_updated`
|
- `last_updated`
|
||||||
|
|
||||||
If the string does not match the template format, the original string is returned.
|
The function replaces any template found in the supplied string with the requested value, or an error message on failure.
|
||||||
Otherwise the requested value is returned, or an error message on failure.
|
|
||||||
|
@ -178,20 +178,22 @@ if (!window.cardTools){
|
|||||||
};
|
};
|
||||||
|
|
||||||
cardTools.parseTemplate =
|
cardTools.parseTemplate =
|
||||||
(str) => {
|
(text, error) => {
|
||||||
if(!str || !str.startsWith('[[ ') || !str.endsWith(' ]]'))
|
const _parse = (str) => {
|
||||||
return str;
|
try {
|
||||||
try {
|
str = str.replace(/^\[\[\s+|\s+\]\]$/g, '')
|
||||||
str = str.replace(/^\[\[\s+|\s+\]\]$/g, '')
|
const parts = str.split(".");
|
||||||
const parts = str.split(".");
|
let v = cardTools.hass.states[`${parts[0]}.${parts[1]}`];
|
||||||
let v = cardTools.hass.states[`${parts[0]}.${parts[1]}`];
|
parts.shift();
|
||||||
parts.shift();
|
parts.shift();
|
||||||
parts.shift();
|
parts.forEach(item => v = v[item]);
|
||||||
parts.forEach(item => v = v[item]);
|
return v;
|
||||||
return v;
|
} catch {
|
||||||
} catch {
|
return error || `[[ Template matching failed ${str} ]]`;
|
||||||
return `[[ Template matching failed ${str} ]]`;
|
}
|
||||||
}
|
}
|
||||||
|
text = text.replace(/(\[\[\s.*?\s\]\])/g, (str, p1, offset, s) => _parse(str));
|
||||||
|
return text;
|
||||||
}
|
}
|
||||||
|
|
||||||
window.cardTools = cardTools;
|
window.cardTools = cardTools;
|
||||||
|
Loading…
x
Reference in New Issue
Block a user