Template Variables

Hi all,

Is there any primer type documentation on template variables? Using web examples I have got a few things done, like where a value follows a particular word or phrase, but I am struggling with other formats.

A couple of examples:

  1. I have an SNMP poll for CPU utilisation that returns a value like “55%”, but I need to strip off the “%” in order for HASS to work with it.
  2. Another SNMP poll for temperature returns a value like “21C/70F”, for which I need to strip down to the integer for degrees C.

Many thanks,
James

Go to Dev tools/templates and play with it.
Auswahl_288

1 Like

If value is 55% then this template will extract everything except the last character:

{{ value[:-1] }}

It’s using python’s ability to slice strings:

If value is 20C/70F then this template will split it (at the / character) into a list containing two items. The list is zero-based so the very first item is the zeroth item. The template chooses the zeroth item and gets everything except the last character:

{{ value.split('/')[0][:-1] }}

It is using a python method called split which is inherent to all strings.

https://www.tutorialspoint.com/python/string_split.htm

Here is a screenshot of the Template Editor. The template’s results are shown on the right hand side:

Screenshot from 2020-02-23 07-47-42

2 Likes

Thanks, that was really helpful, and I have solved a few more since too.

1 Like

You’re welcome!

Seeing that you are new to the community, I’ll introduce you to a custom of this forum. After you get a reply that answers your question, mark the reply with the Solution tag. Only the author of a topic (you’re the author of this topic) can select a post and tag it as being the Solution to the stated question or problem.

Performing this step is beneficial to other members of this community. First, a checkmark will automatically appears next to the topic’s title. This signals to other users that the topic has a Solution. In addition, a link will appear below the first post that leads to the Solution post. All of this makes it easier for other users, who have the same question, find answers. Lastly, it gives credit to the person who supplied the Solution.