From 1de164363c5bd227c7af8e5a55b8f867ffd498ad Mon Sep 17 00:00:00 2001 From: Paul Donohue Date: Mon, 17 Feb 2025 21:46:48 -0500 Subject: [PATCH] Adjust variables to support the same template syntax as other sections Specifically, support ${} in variables, multiple templates in variables, and nested templates in data structures. --- README.md | 2 +- src/config-template-card.ts | 14 ++++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 943aab1..24529ce 100644 --- a/README.md +++ b/README.md @@ -200,7 +200,7 @@ views: Both arrays and objects are supported, just like in card's local variables. It is allowed to mix the two types, i.e. use an array in dashboard variables and an object in card variables, or the other way around. If both definitions are arrays, then dashboard variables are put first in `vars`. In the mixed mode, `vars` have array indices and as well as variable names. -### Note: All templates must be enclosed by `${}` +### Note: All templates must be enclosed by `${}`, except when defining variables. [Troubleshooting](https://github.com/thomasloven/hass-config/wiki/Lovelace-Plugins) diff --git a/src/config-template-card.ts b/src/config-template-card.ts index 30e518e..5c2e4d9 100644 --- a/src/config-template-card.ts +++ b/src/config-template-card.ts @@ -174,8 +174,8 @@ export class ConfigTemplateCard extends LitElement { private _evaluateVars(): void { const vars: Record & any[] = []; - const namedVars: Record = {}; - const arrayVars: any[] = []; + let namedVars: Record = {}; + let arrayVars: any[] = []; globalThis.hass = this.hass; // Used by _evalWithVars() Object.assign(this._varMgr, { @@ -204,16 +204,18 @@ export class ConfigTemplateCard extends LitElement { } } + arrayVars = structuredClone(arrayVars); for (let v of arrayVars) { - if (isString(v)) { v = this._evalWithVars(v); } - else { v = structuredClone(v); } + if (isString(v) && !v.includes('${')) { v = this._evalWithVars(v); } + else { v = this._evaluateStructure(v); } vars.push(v); } + namedVars = structuredClone(namedVars); for (const varName in namedVars) { let v = namedVars[varName]; - if (isString(v)) { v = this._evalWithVars(v); } - else { v = structuredClone(v); } + if (isString(v) && !v.includes('${')) { v = this._evalWithVars(v); } + else { v = this._evaluateStructure(v); } vars[varName] = v; this._varMgr._evalInitVars += `var ${varName} = vars['${varName}'];\n`; }