From 8cddccb83466d2db29f832085e2c701bdef6b254 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Wiedemann?= Date: Thu, 27 Jul 2023 19:00:26 +0000 Subject: [PATCH] feat(variables): A variable can depend on another variable based on their name's alphabetical order Fix #656 --- README.md | 20 +++++++++++++++++++- src/button-card.ts | 13 ++++++++++--- 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 246b7dd..966711b 100644 --- a/README.md +++ b/README.md @@ -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: @@ -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 diff --git a/src/button-card.ts b/src/button-card.ts index 3ef4adc..4c93220 100644 --- a/src/button-card.ts +++ b/src/button-card.ts @@ -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);