feat(templates): new `relativeTime` function to display a relative time in a template and update it automatically
Fix #701
This commit is contained in:
parent
1bc8f99501
commit
965a3d7b97
|
@ -342,6 +342,7 @@ Inside the javascript code, you'll have access to those variables:
|
|||
- `units` (string): Will force the units to be the value of that parameter.
|
||||
- To skip one or multiple parameter while calling the function, use `undefined`. Eg. `localize(states['sensor.temperature'], undefined, 1, undefined, 'Celcius')`
|
||||
- `formatDateTime(date)`, `formatShortDateTimeWithYear(date)`, `formatShortDateTime(date)`, `formatDateTimeWithSeconds(date)`, `formatDateTimeNumeric(date)`: Some helper functions to format a date time string or Date object. Name are pretty explicit. Example: `return formatDateTime(entity.attribute.last_changed)`
|
||||
- `relativeTime(date)`: Returns an lit-html template which will render a relative time and update automatically. `date` should be a string. Usage for eg.: `return relativeTime(entity.last_changed)`
|
||||
|
||||
See [here](#templates-support) for some examples or [here](#custom-fields) for some crazy advanced stuff using templates!
|
||||
|
||||
|
|
|
@ -334,6 +334,20 @@ class ButtonCard extends LitElement {
|
|||
return formatDateTimeNumeric(new Date(date), this._hass!.locale, this._hass!.config);
|
||||
}
|
||||
|
||||
private _relativeTime(date: string | undefined) {
|
||||
if (date) {
|
||||
return html`
|
||||
<ha-relative-time
|
||||
id="relative-time"
|
||||
class="ellipsis"
|
||||
.hass="${this._hass}"
|
||||
.datetime="${date}"
|
||||
></ha-relative-time>
|
||||
`;
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
private _evalTemplate(state: HassEntity | undefined, func: any): any {
|
||||
/* eslint no-new-func: 0 */
|
||||
try {
|
||||
|
@ -350,6 +364,7 @@ class ButtonCard extends LitElement {
|
|||
`formatShortDateTime`,
|
||||
`formatDateTimeWithSeconds`,
|
||||
`formatDateTimeNumeric`,
|
||||
`relativeTime`,
|
||||
`'use strict'; ${func}`,
|
||||
).call(
|
||||
this,
|
||||
|
@ -365,6 +380,7 @@ class ButtonCard extends LitElement {
|
|||
this._formatShortDateTime.bind(this),
|
||||
this._formatDateTimeWithSeconds.bind(this),
|
||||
this._formatDateTimeNumeric.bind(this),
|
||||
this._relativeTime.bind(this),
|
||||
);
|
||||
} catch (e: any) {
|
||||
const funcTrimmed = func.length <= 100 ? func.trim() : `${func.trim().substring(0, 98)}...`;
|
||||
|
|
Loading…
Reference in New Issue