--- layout: page title: "Templating" description: "Instructions on how to use the templating feature of Home Assistant." date: 2015-12-12 12:00 sidebar: true comments: false sharing: true footer: true redirect_from: /topics/templating/ --- This is an advanced feature of Home Assistant. You'll need a basic understanding of the following things: - [Home Assistant architecture](/developers/architecture/), especially states. - [State object](/topics/state_object/) Templating is a powerful feature in Home Assistant that allows the user control over information that is going into and out of the system. It is used for: - Formatting outgoing messages in, for example, the [notify](/components/notify/) platforms and [alexa](/components/alexa/) component. - Process incoming data from sources that provide raw data, like [MQTT](/components/mqtt/), [`rest` sensor](/components/sensor.rest/) or the [`command_line` sensor](/components/sensor.command_line/). - [Automation Templating](/docs/automation/templating/). ## {% linkable_title Building templates %} Templating in Home Assistant is powered by the [Jinja2](http://jinja.pocoo.org/) templating engine. This means that we are using their syntax and make some custom Home Assistant variables available to templates during rendering. We will not go over the basics of the syntax, as Jinja2 does a lot better job at this in their [Jinja2 documentation](http://jinja.pocoo.org/docs/dev/templates/).
The frontend has a template editor developer tool to help develop and debug templates.
Templates can get big pretty fast. To keep a clear overview, consider using YAML multiline strings to define your templates: {% raw %} ```yaml script: msg_who_is_home: sequence: - service: notify.notify data_template: message: > {% if is_state('device_tracker.paulus', 'home') %} Ha, Paulus is home! {% else %} Paulus is at {{ states('device_tracker.paulus') }}. {% endif %} ``` {% endraw %} [Jinja2](http://jinja.pocoo.org/) supports a wide variety of operations: - [Mathematical operation](http://jinja.pocoo.org/docs/dev/templates/#math) - [Comparisons](http://jinja.pocoo.org/docs/dev/templates/#comparisons) - [Logic](http://jinja.pocoo.org/docs/dev/templates/#logic) ## {% linkable_title Home Assistant template extensions %} Home Assistant adds extensions to allow templates to access all of the current states: - Iterating `states` will yield each state sorted alphabetically by entity ID. - Iterating `states.domain` will yield each state of that domain sorted alphabetically by entity ID. - `states.sensor.temperature` returns the state object for `sensor.temperature`. - `states('device_tracker.paulus')` will return the state string (not the object) of the given entity or `unknown` if it doesn't exist. - `is_state('device_tracker.paulus', 'home')` will test if the given entity is the specified state. - `state_attr('device_tracker.paulus', 'battery')` will return the value of the attribute or None if it doesn't exist. - `is_state_attr('device_tracker.paulus', 'battery', 40)` will test if the given entity attribute is the specified state (in this case, a numeric value). - `now()` will be rendered as current time in your time zone. - For specific values: `now().second`, `now().minute`, `now().hour`, `now().day`, `now().month`, `now().year`, `now().weekday()` and `now().isoweekday()` - `utcnow()` will be rendered as UTC time. - For specific values: `utcnow().second`, `utcnow().minute`, `utcnow().hour`, `utcnow().day`, `utcnow().month`, `utcnow().year`, `utcnow().weekday()` and `utcnow().isoweekday()`. - `as_timestamp()` will convert datetime object or string to UNIX timestamp - `distance()` will measure the distance in kilometers between home, entity, coordinates. - `closest()` will find the closest entity. - `float` will format the output as float. - `strptime(string, format)` will parse a string to a datetime based on a [format][strp-format]. - `log(value, base)` will take the logarithm of the input. When the base is omitted, it defaults to `e` - the natural logarithm. Can also be used as a filter. - `sin(value)` will return the sine of the input. Can be used as a filter. - `cos(value)` will return the cosine of the input. Can be used as a filter. - `tan(value)` will return the tangent of the input. Can be used as a filter. - `sqrt(value)` will return the square root of the input. Can be used as a filter. - `e` mathematical constant, approximately 2.71828. - `pi` mathematical constant, approximately 3.14159. - `tau` mathematical constant, approximately 6.28318. - Filter `round(x)` will convert the input to a number and round it to `x` decimals. - Filter `timestamp_local` will convert an UNIX timestamp to local time/data. - Filter `timestamp_utc` will convert an UNIX timestamp to UTC time/data. - Filter `timestamp_custom(format_string, local_boolean)` will convert an UNIX timestamp to a custom format, the use of a local timestamp is default, supporting [Python format options](https://docs.python.org/3/library/time.html#time.strftime). - Filter `max` will obtain the largest item in a sequence. - Filter `min` will obtain the smallest item in a sequence. - Filter `regex_match(string, find, ignorecase=FALSE)` will match the find expression at the beginning of the string using regex. - Filter `regex_search(string, find, ignorecase=FALSE)` will match the find expression anywhere in the string using regex. - Filter `regex_replace(string, find='', replace='', ignorecase=False)` will replace the find expression with the replace string using regex. - Filter `regex_findall_index(string, find='', index=0, ignorecase=False)` will find all regex matches of find in string and return the match at index (findall returns an array of matches). - Filter `bitwise_and(value_one, value_two)` perform a bitwise and(&) operation with two values. - Filter `bitwise_or(value_one, value_two)` perform a bitwise or(\|) operation with two values. - Filter `base64_encode` convert given value to a Base64 encoded string. - Filter `base64_decode` convert given Base64 value to a regulary string. - Filter `ordinal` convert a number into a speakable ordinal text. [strp-format]: https://docs.python.org/3.6/library/datetime.html#strftime-and-strptime-behaviorIf your template uses an `entity_id` that begins with a number (example: `states.device_tracker.2008_gmc`) you must use a bracket syntax to avoid errors caused by rendering the `entity_id` improperly. In the example given, the correct syntax for the device tracker would be: `states.device_tracker['2008_gmc']`
## {% linkable_title Templates using `now()` %}Rendering templates with time (`now()`) is dangerous as updates only trigger templates in sensors based on entity state changes.
## {% linkable_title Priority of operators %} The default priority of operators is that the filter (`|`) has priority over everything except brackets. This means that: {% raw %} ```yaml {{ states('sensor.temperature') | float / 10 | round(2) }} ``` {% endraw %} Would round `10` to 2 decimal places, then divide `states('sensor.temperature')` by that. ## {% linkable_title Home Assistant template extensions %} In templates, besides the normal [state object methods and properties](/topics/state_object/), there are also some extra things available: - `states.sensor.temperature.state_with_unit` will print the state of the entity and, if available, the unit. ## {% linkable_title Examples %} To test a template, go to the