Skip to content

Commit

Permalink
Adjust variables to support the same template syntax as other sections
Browse files Browse the repository at this point in the history
Specifically, support ${} in variables, multiple templates in variables,
and nested templates in data structures.
  • Loading branch information
PaulSD committed Feb 18, 2025
1 parent ef94749 commit 1de1643
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 7 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
14 changes: 8 additions & 6 deletions src/config-template-card.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,8 @@ export class ConfigTemplateCard extends LitElement {

private _evaluateVars(): void {
const vars: Record<string, any> & any[] = [];
const namedVars: Record<string, any> = {};
const arrayVars: any[] = [];
let namedVars: Record<string, any> = {};
let arrayVars: any[] = [];

globalThis.hass = this.hass; // Used by _evalWithVars()
Object.assign(this._varMgr, {
Expand Down Expand Up @@ -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`;
}
Expand Down

0 comments on commit 1de1643

Please sign in to comment.