1.3.0 • Published 9 months ago

ha-nunjucks v1.3.0

Weekly downloads
-
License
ISC
Repository
github
Last release
9 months ago

ha-nunjucks

License Project Maintenance GitHub Activity Community Forum

Github

A wrapper for nunjucks for use with Home Assistant frontend custom components to render templates instanteneously at HTML render time. This repository offers an easy way for developers to add templating support to Home Assistant custom cards.

What is nunjucks?

Nunjucks is a templating engine for JavaScript that is heavily inspired by jinja2. Home Assistant uses jinja2 to process templates in card configurations on the backend, so the syntax of jinja2 and Nunjucks is virtually the same. This makes it an excellent alternative to Home Assistant core jinja2 templating for custom cards.

While some Home Assistant native cards support templating for certain fields, implementing proper Home Assistant jinja2 template support in custom cards can be difficult. Additionally Home Assistant jinja2 templates are processed by the Python backend, and can take several seconds to render. Nunjucks templates are processed by the frontend using the frontend hass object before your custom card's HTML is rendered, making nunjucks templating synchronous, instanteous. and much faster than traditional jinja2 templates.

Usage

Install using npm:

npm install ha-nunjucks

Then import renderTemplate from ha-nunjucks and provide it with the hass object and a template string you want to process.

import { renderTemplate } from 'ha-nunjucks';

const renderedString = renderTemplate(this.hass, templateString);

That's it! The result of renderTemplate is the rendered template for you to use. In unit and integration testing render time is under 1 ms and shouldn't cause any latency in your projects.

Rather than rendering templates on the backend, nunjucks renders templates on the frontend. This repository uses the Home Assistant object present in all custom cards to read entity state data.

You can also provide context to the renderTemplate function to pass to nunjucks if you want to make additional variables or project specific functions available to your users for use in templates.

import { renderTemplate } from 'ha-nunjucks';

const context = {
  foo: 'bar',
  doThing(thing: string) {
    return `doing ${thing}!`;
  },
  config: {
    entity: 'foo.bar',
    attribute: 'baz_bah',
  },
};

const renderedString = renderTemplate(this.hass, templateString, context);

Return Types

renderTemplate will return a string unless the result is true or false (not case sensitive), in which case it will return a boolean.

When the return type is expected to be a number, end users should cast these values using the nunjucks int or float filters to prevent undesired behavior caused by JavaScript forcing operations between disparate variable types. Numbers are not returned by default to prevent leading and trailing zeroes from being truncated from numerical strings.

renderTemplate will return an empty string for strings that may have been cast from nullish non-numerical values, such as undefined, null, and None (case sensitive).

Available Extensions

The vast majority of the Home Assistant template extensions have been implemented into this package. If there are functions that you use that are not currently supported or don't behave exactly like their jinja2 versions, please make a feature request or try adding it to the project yourself and create a pull request.

Template extensions can be functions, tests, filters, and/or constants. Functions are called like a regular programming function, such as states() or floors(). Filters are added to the end of a string using a pipe character like 123.45 | int or "light.lounge" | state_attr("brightness"). Tests are functions which return booleans and can be used in an if statement like if "foo" is string_like, not to be confused with functions that return booleans and can be used in if statements like if is_state("light.lounge", "on"). Contants are static values, and are just called as is like {{ True }} or {{ pi }}.

In addition to the template extensions implemented in this package, you also have access to the nunjucks builtin functions and filters. Read the nunjucks templating documentation for more information.

Python Constants

These just remap Python built-in constants to JavaScript ones.

PythonJavaScript
Truetrue
Falsefalse
Nonenull

Frontend Data Hass Object

The frontend data hass object has been exposed to users to call upon.

Because entity IDs contain periods in them, you cannot use dot notation when accessing an entity's state object using it. You have to use bracket notation like so:

{{ hass.states["light.sunroom_ceiling"].state }}

For convenience, the hass.states object is rebuilt as a separate object that can be accessed with dot notation. Because of JavaScript limitations not allowing for functions and object to share the same name, it has been named _states.

{{ _states.light.sunroom_ceiling.state }}

You do have to use bracket notation for arrays within state objects.

{{ _states.light.sunroom_ceiling.attributes.supported_color_modes[0] }}

States

Functions used to determine an entity's state or an attribute.

NameTypeArgumentsDescription
statesfunction, filterentity_id, rounded (optional), with_unit (optional)Returns the state string of the given entity. Optionally round numerical states and append the unit of measurement.
is_statefunction,entity_id, valueCompares an entity's state with a specified state or list of states and returns true or false.
state_attrfunction, filterentity_id, attributeReturns the value of the attribute or undefined if it doesn't exist.
is_state_attrfunctionentity_id, attribute, valueTests if the given entity attribute is the specified value.
has_valuefunction, filterentity_idTests if the given entity is not unknown or unavailable.

State Translated

NameTypeArgumentsDescription
state_translatedfunction, filterentity_id, state (optional)Returns the formatted and translated state of an entity or provided state using a language that is currently configured in the general settings.
attr_name_translatedfunction, filterentity_id, attr_nameReturns the formatted and translated attribute name of an entity using a language that is currently configured in the general settings.
attr_value_translatedfunction, filterentity_id, attr_name, attr_value (optional)Returns the formatted and translated attribute value of an entity or provided attribute value using a language that is currently configured in the general settings.

Groups

NameTypeArgumentsDescription
expandfunction, filterargsRetrieve state objects for provided entities and sort. Expands group entities into their members.

Entities

NameTypeArgumentsDescription
is_hidden_entityfunctionentity_idReturns whether an entity has been hidden.

Devices

NameTypeArgumentsDescription
device_entitiesfunction, filterdevice_idReturns a list of entities that are associated with a given device ID.
device_attrfunction, filterdevice_or_entity_id, attr_nameReturns the value of attr_name for the given device or entity ID.
is_device_attrfunctiondevice_or_entity_id, attr_name, attr_valueReturns whether the value of attr_name for the given device or entity ID matches attr_value.
device_idfunction, filterentity_idReturns the device ID for a given entity ID or device name.

Floors

NameTypeArgumentsDescription
floorsfunctionReturns the full list of floor IDs that include an area.
floor_idfunction, filterlookup_valueReturns the floor ID for a given device ID, entity ID, area ID, or area name.
floor_namefunction, filterlookup_valueReturns the floor name for a given device ID, entity ID, area ID, area name, or floor ID.
floor_areasfunction, filterfloor_name_or_idReturns the list of area IDs tied to a given floor ID or name.

Areas

NameTypeArgumentsDescription
areasfunctionReturns the full list of area IDs.
area_idfunction, filterlookup_valueReturns the area ID for a given device ID, entity ID, or area name.
area_namefunction, filterlookup_valueReturns the area name for a given device ID, entity ID, or area ID.
area_entitiesfunction, filterarea_name_or_idReturns the list of entity IDs tied to a given area ID or name.
area_devicesfunction, filterarea_name_or_idReturns the list of device IDs tied to a given area ID or name.

Entities For An Integration

NameTypeArgumentsDescription
integration_entitiesfunctionintegrationReturns a list of entities that are associated with a given integration.

Labels

NOTE: Labels are not available in the hass object and must be retrieved asynchronously from the Home Assistant backend the first time renderTemplate is called. Since this package is otherwise synchronous, this can cause a race condition where no labels are found the first time renderTemplate is run. This generally resolves itself once the template re-renders.

NameTypeArgumentsDescription
labelsfunction, filterlookup_value (optional)Returns the full list of label IDs, or those for a given area ID, device ID, or entity ID.
label_idfunction, filterlookup_valueReturns the label ID for a given label name.
label_namefunction, filterlookup_valueReturns the label name for a given label ID.
label_areasfunction, filterlabel_name_or_idReturns the list of area IDs tied to a given label ID or name.
label_devicesfunction, filterlabel_name_or_idReturns the list of device IDs tied to a given label ID or name.
label_entitiesfunction, filterlabel_name_or_idReturns the list of entity IDs tied to a given label ID or name.

Immediate If

A shorthand for an if else statement.

NameTypeArgumentsDescription
iiffunction, filtercondition, if_true, if_false, if_noneImmediate if. Returns the value of if_true if the condition is true, the value of if_false if it's false, and the value of if_none if it's undefined, null, or an empty string. All arguments except condition are optional. Cannot be used as a filter.

Time

NOTE:

  • JS Date does not support time precision below 1 millisecond, while Python datetime supports microsecond precision. Microsecond arguments are not available for these methods.
  • JS Date is not as good at handling timezones as Python datetime. Be careful about timezone differences! You can try to account for this using the utc flags and/or by including a timezone offset in a datetime string to parse using as_datetime or strptime.
  • Including time extensions in your templates does not cause them to refresh more regularly by themselves, although they will still update whenever the hass object does. If you are a developer, you have to implement this behavior yourself in your custom cards.
NameTypeArgumentsDescription
nowfunctionReturns a datetime object that represents the current time in your time zone.
utcnowfunctionReturns a datetime object of the current time in the UTC timezone.
today_atfunction, filtervalueConverts a string containing a military time format to a datetime object with today’s date in your time zone. Defaults to midnight (00:00).
as_datetimefunction, filtervalue, fallback (optional), utc (default true)Converts a string containing a timestamp, or valid UNIX timestamp, to a datetime object. If that fails, it returns the fallback value or, if omitted, raises an error. When the input is already a datetime object it will be returned as is. in case the input is a datetime.date object, midnight will be added as time.
as_timestampfunction, filtervalue, fallback (optional)Converts a datetime object or string to UNIX timestamp. If that fails, returns the fallback value, or if omitted raises an error.
as_localfunction, filtervalueConverts a datetime object to local time.
strptimefunctionvalue, format, fallback (optional), utc (default false)Parses a string based on a format and returns a datetime object. If that fails, it returns the default value or, if omitted, raises an error.
time_sincefunction, filtervalue, precision (default 1)Returns a human readable string indicating the difference between now and an input past datetime object. precision indicates how many units (years, months, days, hours, minutes, seconds) to use, with the last unit being rounded and 0 being the same as 6. If the input datetime is in the past it returns the input. If the input datetime is not a datetime object it returns nothing.
time_untilfunction, filtervalue, precision (default 1)Returns a human readable string indicating the difference between now and an input future datetime object. precision indicates how many units (years, months, days, hours, minutes, seconds) to use, with the last unit being rounded and 0 being the same as 6. If the input datetime is in the future it returns the input. If the input datetime is not a datetime object it returns nothing.
as_timedeltafunction, filtervalueConverts a string to a timedelta object. Expects data in the format DD HH:MM:SS.uuuuuu, DD HH:MM:SS,uuuuuu, or as specified by ISO 8601 (e.g. P4DT1H15M20S which is equivalent to 4 1:15:20) or PostgreSQL’s day-time interval format (e.g. 3 days 04:05:06).
timestamp_localfiltervalue, fallback (optional)Converts a UNIX timestamp to the ISO format string representation as date/time in your local timezone. If that fails, returns the fallback value, or if omitted raises an error.
timestamp_utcfiltervalue, fallback (optional)Converts a UNIX timestamp to the ISO format string representation as date/time in UTC timezone. If that fails, returns the fallback value, or if omitted raises an error.
timestamp_customfiltervalue, format, local (default true), fallback (optional)Converts a UNIX timestamp to its string representation based on a custom format. Uses the local timezone by default. If that fails, returns the fallback value, or if omitted raises an error.

In addition to these functions, you have access to a datetime library which emulates the Python datetime module in TypeScript. You can instantiate date, time, datetime, and timedelta objects using the dt object. You can then access it's class methods using these objects. To use the static method and constants of these classes, you can reference them directly without prefixing them with dt. See the README in the datetime repository linked above for more information on how to use it.

NameTypeArgumentsDescription
dtobjectThe datetime object, which contains constructor functions for date, datetime, time, and timedelta along with some constants.
dt.datefunctionyear, month, dayReturns a date object.
dt.datetimefunctionyear, month, day, hour (default 0), minute (default 0), second (default 0), millisecond (default 0), utc (default false)Returns a datetime object, like the ones used by the functions above.
dt.timefunctionhour (default 0), minute (default 0), second (default 0), millisecond (default 0)Returns a time object.
dt.timedeltafunctiondays (optional), seconds (optional), milliseconds (optional), minutes (optional), hours (optional), weeks (optional)Returns a timedelta object.
dateclassThe date class, which has static methods which can be called upon.
datetimeclassThe datetime class, which has static methods which can be called upon.
timeclassThe time class, which has static methods which can be called upon.
timedeltaclassThe timedelta class, which has static methods which can be called upon.

To/From JSON

NameTypeArgumentsDescription
to_jsonfilterobj, ensure_ascii, pretty_print, sort_keysTurn an object into a JSON string. ensure_ascii converts unicode characters into escape sequences. pretty_print formats the output with new lines and an indent of two spaces. sort_keys sorts the keys of the JSON object. Consider using the nunjucks safe filter with this
from_jsonfiltervalueParse a string as JSON.

Distance

NameTypeArgumentsDescription
distancefunctionargsMeasures the distance between home, an entity, or coordinates. The unit of measurement (kilometers or miles) depends on the system’s configuration settings.
closestfunction, filterargsFinds the closest entity to home, or the first entity or coordinate if multiple provided. Arguments can be entity IDs, domains, entity state objects, coordinate pairs, or arrays.

Contains

NameTypeArgumentsDescription
containsfilter, testlist, valueReturns if an element is in a list.

Numeric

NameTypeArgumentsDescription
floatfunction, filtervalue, fallback (optional)Converts a value to a float. If that fails, it returns the fallback value or, if omitted, raises an error.
is_numberfunction, filtervalueReturns true if a value can be parsed as a number.
intfunction, filtervalue, fallback (optional)Converts a value to an integer. If that fails, it returns the fallback value or, if omitted, raises an error.
boolfunction, filtervalue, fallback (optional )Converts a value to a boolean based on the human readable truthiness of it, case insensitive. Non-zero integers, true, yes, on, enable, and 1 return true. 0, false, no, off, disable and 0 return false. If the value's human readable truthiness cannot be determined, returns the fallback value or, if omitted, raises an error.
logfunction, filtervalue, base (default e), fallback (optional)Returns the logarithm of a value, defaulting to the natural logarithm if no base is provided. If that fails, it returns the fallback value or, if omitted, raises an error.
sinfunction, filtervalue, fallback (optional)Returns the sine of a value. If that fails, it returns the fallback value or, if omitted, raises an error.
cosfunction, filtervalue, fallback (optional)Returns the cosine of a value. If that fails, it returns the fallback value or, if omitted, raises an error.
tanfunction, filtervalue, fallback (optional)Returns the tangent of a value. If that fails, it returns the fallback value or, if omitted, raises an error.
asinfunction, filtervalue, fallback (optional)Returns the arcus sine of a value. If that fails, it returns the fallback value or, if omitted, raises an error.
acosfunction, filtervalue, fallback (optional)Returns the arcus cosine of a value. If that fails, it returns the fallback value or, if omitted, raises an error.
atanfunction, filtervalue, fallback (optional)Returns the arcus tangent of a value. If that fails, it returns the fallback value or, if omitted, raises an error.
atan2function, filtery, x, fallback (optional)Returns the four quadrant arcus tangent of y / x. If that fails, it returns the fallback value or, if omitted, raises an error.
sqrtfunction, filtervalue, fallback (optional)Returns the square root of a value. If that fails, it returns the fallback value or, if omitted, raises an error.
maxfunction, filterargsReturns the largest argument provided, flattening any arrays.
minfunction, filterargsReturns the smallest argument provided, flattening any arrays.
averagefunction, filtervalues, fallback (optional)Returns the average of an array, flattening any subarrays. If a non-numeric value is detected or the array is empty, it returns the fallback value or, if omitted, raises an error.
medianfunction, filtervalues, fallback (optional)Returns the median of an array, flattening any subarrays. If a non-numeric value is detected or the array is empty, it returns the fallback value or, if omitted, raises an error.
statistical_modefunction, filtervalues, fallback (optional)Returns the mode of an array, flattening any subarrays. If a non-numeric value is detected or the array is empty, it returns the fallback value or, if omitted, raises an error.
econstantMathematical constant Euler's number.
piconstantMathematical constant pi.
tauconstantMathematical constant tau.
infconstantMathematical conceptual value infinity.
roundfiltervalue, precision, method, fallback (optional)Converts the input to a number and rounds it to precision decimals. It has four modes - even, floor, ceil, and half. If the input value is not a number, it returns the fallback value, or, if omitted, raises an error.
bitwise_andfiltervalue_one, value_twoPerforms a bitwise and(&) operation with two values.
bitwise_orfiltervalue_one, value_twoPerforms a bitwise or(|) operation with two values.
bitwise_xorfiltervalue_one, value_twoPerforms a bitwise xor(^) operation with two values.
bitwise_notfiltervaluePerforms a bitwise not(~) operation with one value.
ordfiltervalueReturns an integer representing a character's (string of length one) Unicode code point.
multiplyfiltervalue, argConverts the input to a number and multiplies it by the argument.
addfiltervalue, argConverts the input to a number and adds it to the argument.

Complex Type Checking

NameTypeArgumentsDescription
listtestvalueTests if a value is a list/array.
settestvalueTests if a value is a set.
datetimetestvalueTests if a value is a datetime.
string_liketestvalueTests if a value is a string, bytes, or bytearray.

Type Conversions

NameTypeArgumentsDescription
setfunctionargsConvert a list/array to a set. Removes duplicates.
listfunctionargsConvert a set to an array. Does not remove duplicates.

Iterating Multiple Objects

NameTypeArgumentsDescription
zipfunctionargsUse to iterate over multiple collections in one operation. If given one array will perform the opposite action and unzip the list.

Regular Expressions

NOTE: The format of regular expressions in nunjucks is different than jinja2. You may want to read the Nunjucks and MDN documentation.

NameTypeArgumentsDescription
matchtestvalue, findMatches the find string at the beginning of the value string using regex.
searchtestvalue, findMatches the find string anywhere in the value string using regex.
testtestvalue, findMatches the find regular expression in the value string usign regex. Regular expressions should be preceded by r, like r/foobar/g.
regex_replacefiltervalue, find (default ''), replace (default '')Replaces the find expression with the replace expression string using RegEx.
regex_findallfiltervalue, find (default '')Finds all RegEx matches of the find expression in value and returns an array of matches.
regex_findall_indexfiltervalue, find (default ''), index (default 0)Performs a RegEx find all but returns the match at a provided index.

Miscellaneous

Functions that are not from the Home Assistant templating documentation.

NameArgumentsDescription
match_mediamediaqueryReturns the boolean result of the provided CSS media query.
strvalue, filterReturn the string representation of the input.
1.3.0-beta.32

10 months ago

1.3.0-beta.33

10 months ago

1.3.0-beta.34

10 months ago

1.3.0-beta.35

10 months ago

1.3.0-beta.36

10 months ago

1.3.0-beta.37

10 months ago

1.3.0-beta.38

9 months ago

1.3.0-beta.39

9 months ago

1.3.0-beta.30

10 months ago

1.3.0-beta.31

10 months ago

1.3.0-beta.43

9 months ago

1.3.0-beta.44

9 months ago

1.3.0-beta.45

9 months ago

1.3.0-alpha.10

10 months ago

1.3.0-alpha.15

10 months ago

1.3.0-beta.40

9 months ago

1.3.0-beta.41

9 months ago

1.3.0-beta.42

9 months ago

1.3.0-beta.10

10 months ago

1.3.0-beta.11

10 months ago

1.3.0-beta.12

10 months ago

1.3.0-beta.13

10 months ago

1.3.0-beta.14

10 months ago

1.3.0-alpha.22

10 months ago

1.3.0-beta.15

10 months ago

1.3.0-alpha.23

9 months ago

1.3.0-beta.16

10 months ago

1.3.0-alpha.24

9 months ago

1.3.0-beta.17

10 months ago

1.3.0-alpha.25

9 months ago

1.3.0-alpha.26

9 months ago

1.3.0-alpha.27

9 months ago

1.3.0

9 months ago

1.3.0-beta.18

10 months ago

1.3.0-beta.19

10 months ago

1.3.0-beta.21

10 months ago

1.3.0-beta.1

10 months ago

1.3.0-beta.22

10 months ago

1.3.0-beta.2

10 months ago

1.3.0-beta.23

10 months ago

1.3.0-beta.3

10 months ago

1.3.0-beta.24

10 months ago

1.3.0-beta.4

10 months ago

1.3.0-beta.25

10 months ago

1.3.0-beta.5

10 months ago

1.3.0-beta.26

10 months ago

1.3.0-beta.6

10 months ago

1.3.0-beta.27

10 months ago

1.3.0-beta.7

10 months ago

1.3.0-beta.28

10 months ago

1.3.0-beta.8

10 months ago

1.3.0-beta.20

10 months ago

1.3.0-beta.29

10 months ago

1.3.0-beta.9

10 months ago

1.2.4-alpha.1

1 year ago

1.2.4-alpha.2

1 year ago

1.2.4-alpha.3

1 year ago

1.2.3

1 year ago

1.2.1

1 year ago

1.2.1-beta.1

1 year ago

1.2.0

2 years ago

1.2.0-alpha.1

2 years ago

1.1.0

2 years ago

1.1.0-alpha.1

2 years ago

1.1.0-dev.2

2 years ago

1.1.0-alpha.3

2 years ago

1.0.1

2 years ago

0.0.13

2 years ago

0.0.12

2 years ago

0.0.10

2 years ago

0.0.9

2 years ago

0.0.8

2 years ago

0.0.7

2 years ago

0.0.6

2 years ago

0.0.4

2 years ago

0.0.3

2 years ago

0.0.2

2 years ago

0.0.1

2 years ago

1.0.0

2 years ago