feat: Support for localization in templates
This commit is contained in:
parent
56e0cc6f94
commit
5de2dc9067
|
@ -332,6 +332,7 @@ Inside the javascript code, you'll have access to those variables:
|
|||
- `user`: The user object (equivalent to `hass.user`)
|
||||
- `hass`: The complete `hass` object
|
||||
- `variables`: an object containing all your variables defined in the configuration. See [Variables](#variables)
|
||||
- `localize(entity, state?)`: a function which localizes a state (eg. `localize(entity)`) and returns a string. Takes an entity object as argument (not the state of the entity as we need context) and takes an optional `state` string as argument. If `state` is not provided, it localizes the state of the `entity` (Eg. `localize(entity)` or `localize(states['weather.your_city'])`). If `state` is provided, it localizes `state` in the context of the `entity` (eg. : `localize(states['weather.your_city'], states['weather.your_city'].attributes.forecast[0].condition)`)
|
||||
|
||||
See [here](#templates-support) for some examples or [here](#custom-fields) for some crazy advanced stuff using templates!
|
||||
|
||||
|
|
|
@ -287,10 +287,31 @@ class ButtonCard extends LitElement {
|
|||
return retval;
|
||||
}
|
||||
|
||||
private _localize(stateObj: HassEntity, state?: string): string {
|
||||
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
||||
return computeStateDisplay(
|
||||
this._hass!.localize,
|
||||
stateObj,
|
||||
this._hass!.locale,
|
||||
this._hass!.config,
|
||||
this._hass!.entities,
|
||||
state,
|
||||
);
|
||||
}
|
||||
|
||||
private _evalTemplate(state: HassEntity | undefined, func: any): any {
|
||||
/* eslint no-new-func: 0 */
|
||||
try {
|
||||
return new Function('states', 'entity', 'user', 'hass', 'variables', 'html', `'use strict'; ${func}`).call(
|
||||
return new Function(
|
||||
'states',
|
||||
'entity',
|
||||
'user',
|
||||
'hass',
|
||||
'variables',
|
||||
'html',
|
||||
`localize`,
|
||||
`'use strict'; ${func}`,
|
||||
).call(
|
||||
this,
|
||||
this._hass!.states,
|
||||
state,
|
||||
|
@ -298,6 +319,7 @@ class ButtonCard extends LitElement {
|
|||
this._hass,
|
||||
this._evaledVariables,
|
||||
html,
|
||||
this._localize.bind(this),
|
||||
);
|
||||
} catch (e: any) {
|
||||
const funcTrimmed = func.length <= 100 ? func.trim() : `${func.trim().substring(0, 98)}...`;
|
||||
|
|
Loading…
Reference in New Issue