Skip to content

Commit

Permalink
feat(variables): A variable can depend on another variable based on t…
Browse files Browse the repository at this point in the history
…heir name's alphabetical order

Fix #656
  • Loading branch information
RomRider committed Jul 27, 2023
1 parent 295909b commit 8cddccb
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 4 deletions.
20 changes: 19 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -922,7 +922,9 @@ state:

#### Variables

You can add variables to your templates and overload them in the instance of your button card. This lets you easily work with templates without the need to redefine everything for a small change. An example below:
You can add variables to your templates and overload them in the instance of your button card. This lets you easily work with templates without the need to redefine everything for a small change.

An example below:

```yaml
button_card_templates:
Expand All @@ -947,6 +949,22 @@ button_card_templates:
# name will be "My local Value"
```

Variables are evaluated in their alphabetical order based on their name. That means a variable named `b` can depend on a variable named `a`, but variable named `a` can't depend on a variable named `b`.

```yaml
### This works
variables:
index: 2
value: '[[[ return variables.index + 2; ]]]'
name: '[[[ return variable.value; ]]]' # would return 4
### This doesn't work
variables:
z_index: 2
value: '[[[ return variables.z_index + 2; ]]]' # This would fail because z comes after v in the alphabet.
name: '[[[ return variable.value; ]]]'
```

## Installation

### Manual Installation
Expand Down
13 changes: 10 additions & 3 deletions src/button-card.ts
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,16 @@ class ButtonCard extends LitElement {
if (!this._config || !this._hass) return html``;
this._stateObj = this._config!.entity ? this._hass!.states[this._config!.entity] : undefined;
try {
this._evaledVariables = this._config!.variables
? this._objectEvalTemplate(this._stateObj, this._config!.variables)
: {};
this._evaledVariables = {};
if (this._config?.variables) {
const variablesNameOrdered = Object.keys(this._config.variables).sort();
variablesNameOrdered.forEach((variable) => {
this._evaledVariables[variable] = this._getTemplateOrValue(
this._stateObj,
this._config!.variables![variable],
);
});
}
return this._cardHtml();
} catch (e: any) {
if (e.stack) console.error(e.stack);
Expand Down

0 comments on commit 8cddccb

Please sign in to comment.