Icon_color template

Hello I am trying to make an icon change color based on the state of an attribute. My sensor state returns a converted time with unit, so I added the seconds attribute to try to draw from that. I’ve been at this a couple of hours now. The first two work in the template tester in Dev Tools, but only returns the icon_color as the template again, whereas the last one only returns gray. I am simply trying to make the icon red if it has been up less than 10 minutes, yellow if it has been up less than 2 hours, and green otherwise. I’ve been trying this since the template returned red, now I’ve been trying so long it returns green, just not on the actual icon.
The template in configuration.yaml

  - sensor:
      - name: Uptime - Counter
        state: >- 
          {% set time = as_timestamp(now()) - as_timestamp(states('sensor.uptime')) %}
          {% set minutes = ((time % 3600) / 60) | int %}
          {% set hours = ((time % 86400) / 3600) | int %}
          {% set days = (time / 86400) | int %}

          {% if time < 60 -%}
            Less than a minute
          {%- else -%}
            {%- if days > 0 -%}
              {{ days~" Days "}}
            {%- endif -%}
            {%- if hours > 0 -%}
              {{ hours~" Hours " }}
            {%- endif -%}
            {%- if minutes > 0 -%}
              {{ (minutes + 1 )~" Minutes " }}
            {%- endif -%}
          {%- endif %}  
        icon: >- 
          {% set time = as_timestamp(now()) - as_timestamp(states('sensor.uptime')) %} 
          {% if time < 7200 -%}
            mdi:clock-alert-outline
          {%- else -%}
            mdi:clock-check-outline
          {%- endif %}   
        attributes:
          seconds: >
            {{ (as_timestamp(now()) - as_timestamp(states('sensor.uptime'))) | round(2) }}

and in customize.yaml I have tried MANY things.

sensor.uptime_counter: 
  templates:
    icon_color: >
      {% set time = as_timestamp(now()) - as_timestamp(states('sensor.uptime')) %}
        {% if time < 600 -%}
          {{ 'red' }}
        {%- else -%}
          {%- if time < 7200 -%}
            {{ 'yellow' }}
          {%- endif -%}
          {%- if time > 7200 -%}
            {{ 'green' }}
          {%- endif -%}
        {%- endif %}

#This is here to separate the code easier#

sensor.uptime_counter: 
  templates:
    icon_color: >
      {% if state_attr('sensor.uptime_counter', 'seconds') < 600 -%}
        red
      {%- else -%}
        {%- if state_attr('sensor.uptime_counter', 'seconds') < 7200 -%}
          yellow
        {%- endif -%}
        {%- if state_attr('sensor.uptime_counter', 'seconds') > 7200 -%}
          green
        {%- endif -%}
      {%- endif %} 

&& I’ve even tried things along these lines. I feel like I am close on this one, but can’t quite get it.

sensor.uptime_counter: 
  templates:
    icon_color: >
      if (entities['sensor.uptime_counter'].seconds < "600") return 'red';
      if (entities['sensor.uptime_counter'].seconds < "7200") return 'yellow';
      if (entities['sensor.uptime_counter'].seconds < "600") return 'green';
      return 'gray';

Thanks in advance!

None of the customize options support templating.

Templating can only be used in under data:, targegt: and service: in automation actions and script sequences and in configuration options that specifically state they support templates.

And there is no icon_color option. Though you could add it as a custom attribute you still can’t template it.

The way to do this is with card-mod in your dashboard.

It supports templates.

I can tell you that templates do indeed work in customize. Unless I’m mistaken and the following isn’t a template, though I don’t know what else it would be considered.
I was easily able to customize the color of my sensor telling whether or not the computer is active with

sensor.downtime_prolienware:
  templates:
    icon_color: >
      if (state == 'Active') return 'yellow'; if (state == 'Unknown') return 'red';
      return 'gray';

That’s directly from customize.yaml.
Works like a charm. I just don’t know enough about templating to direct state to an attribute instead.

Also to fix your template do this:

    icon_color: >
      {% if state_attr('sensor.uptime_counter', 'seconds') < 600 %}
        red
      {% elif state_attr('sensor.uptime_counter', 'seconds') < 7200 %}
          yellow
      {% elif state_attr('sensor.uptime_counter', 'seconds') >= 7200 %}
          green
      {% endif %} 
1 Like

Well they shouldn’t. Nowhere does it say they do. So you are using an unsupported feature that could break at any time:

For comparison, something that does support a template:

Screenshot 2022-06-15 at 10-12-34 Template

1 Like

Hmmm. Interesting. Well then. That sucks. I really just wanted the color to work for every dash I put this on like my active sensor without too much lovelace customizing.
Can you tell me how to fix this template? I’m sure all I’m doing wrong is directing it to wrong place, I don’t recognize this format, so I’m not sure how to make

      if (entities['sensor.uptime_counter'].seconds

equal

      if state_attr('sensor.uptime_counter', 'seconds')

I’m 90% sure the .seconds is the incorrect part. I don’t mind if this breaks later. I’ve been having a crashing issue every hour and 4 minutes that I think I resolved so I wanted this sensor for that.

This looks like something specific to the custom button card. Where did you see it?

This isn’t jinja either. Are you using CustomUI or something like that?

1 Like

Well, turns out I am using CustomUI, didn’t realize I’d done that. I may have downloaded it when I was new to all of this. I know it is deprecated, so, I’m chasing dreams.

This fork is still supported:

However you would be far better off learning how to use card-mod.

Oh, that’s the fork I am using.

Then it has an example to do what you want:

      templates: # state is a number
        icon_color: >
          if (state < -20) return 'black';
          if (state < -15) return 'navy';
          if (state < -10) return 'darkblue';
          if (state < -5) return 'mediumblue';
          if (state < 0) return 'blue';
          if (state < 5) return 'dodgerblue';
          if (state < 10) return 'lightblue';
          if (state < 15) return 'turquoise';
          if (state < 20) return 'green';
          if (state < 25) return 'darkgreen';
          if (state < 30) return 'orange';
          if (state < 35) return 'crimson';
          return 'firebrick';

The problem here is that state is reported as X Hours X Minutes, so when I use it as is, “minutes” and “hours” gets in the way. No? Honestly I never tried just using state. One moment, I will report back.

sensor.uptime_counter:
  templates:
    icon_color: >
          if (state < 600) return 'red';
          if (state < 7200) return 'yellow';
          if (state >= 7200) return 'green';

reports back “undefined”
I also tried

sensor.uptime_counter:
  templates:
    icon_color: >
          if (seconds < 600) return 'red';
          if (seconds < 7200) return 'yellow';
          if (seconds >= 7200) return 'green';

Same result. I guess I could make a separate sensor that counts just the seconds and push it that way using

if (entities['sensor.new_sensor'].state

For anyone trying to accomplish this… I was able to successfully get the result I was looking for via creating a secondary sensor. This template works with CustomUI via the fork provided above. (Actually may work without it, I noticed I didn’t have the CustomUI resource in the config.)
If you would like to monitor your sensor.uptime in a manner that makes a little more sense than having to click into the entity to read how long it’s been since the timestamp in an easy way, here you go! This can also be applied to other sensors as well, just adjust to your needs. The minutes + 1 is to account for the fact that you can’t properly display seconds in a template since they update every minute with now().

configuration.yaml:

  - sensor:
      - name: Uptime - Counter
        state: >- 
          {% set time = as_timestamp(now()) - as_timestamp(states('sensor.uptime')) %}
          {% set minutes = ((time % 3600) / 60) | int %}
          {% set hours = ((time % 86400) / 3600) | int %}
          {% set days = (time / 86400) | int %}

          {% if time < 60 -%}
            Less than a minute
          {%- else -%}
            {%- if days > 0 -%}
              {{ days~" Days "}}
            {%- endif -%}
            {%- if hours > 0 -%}
              {{ hours~" Hours " }}
            {%- endif -%}
            {%- if minutes > 0 -%}
              {{ (minutes + 1 )~" Minutes " }}
            {%- endif -%}
          {%- endif %}  
        icon: >- 
          {% set time = as_timestamp(now()) - as_timestamp(states('sensor.uptime')) %} 
          {% if time < 7200 -%}
            mdi:clock-alert-outline
          {%- else -%}
            mdi:clock-check-outline
          {%- endif %}   
        attributes:
          seconds: >
            {{ (as_timestamp(now()) - as_timestamp(states('sensor.uptime'))) | round(2) }}
  - sensor:
      - name: Uptime - Counter - Icon Color
        state: >-
          {% set time = as_timestamp(now()) - as_timestamp(states('sensor.uptime')) %} 
          {% if time < 599 %}
            red
          {% elif time > 599 and time < 7199 %}
              yellow
          {% elif time >= 7200 %}
              green
          {% endif %} 
        icon: >- 
          {% set time = as_timestamp(now()) - as_timestamp(states('sensor.uptime')) %} 
          {% if time < 7200 -%}
            mdi:clock-alert-outline
          {%- else -%}
            mdi:clock-check-outline
          {%- endif %}

and then in customize.yaml:

#####DO NOT USE THIS ONE I LEFT IT IN HERE TO SHOW MY MISTAKE#####
sensor.uptime_counter:
  templates:
    icon_color: >
      if (entities['sensor.uptime_counter_icon_color'].state = 'red') return 'red';
      if (entities['sensor.uptime_counter_icon_color'].state = 'yellow') return 'yellow';
      if (entities['sensor.uptime_counter_icon_color'].state = 'green') return 'green';
      return 'gray';

Edit: Weird… It works until I activate the customize… when that is enabled for some reason sensor.uptime_counter_icon_color only produces red in State. Otherwise it works. Even stranger - if you put {{ states('sensor.uptime_counter_icon_color') }} in the Templates of Dev Tools, it produces “yellow” as it should. Anyone have an idea on that? Kinda strange.

Edit 2: GOT IT!!! The issue was really dumb. Needed == instead of =.

sensor.uptime_counter:
  templates:
    icon_color: >
      if (entities['sensor.uptime_counter_icon_color'].state == "red" ) return 'red';
      if (entities['sensor.uptime_counter_icon_color'].state == "yellow" ) return 'yellow';
      if (entities['sensor.uptime_counter_icon_color'].state == "green" ) return 'green';
      return 'gray';

THANK YOU @tom_l for getting me on the correct path.
Do I mark this as Solution? Feels kinda weird since it is my own post.

1 Like

Hi there

I read this post with big interest as I am trying to achieve the same like @Pronown and thought I may post here instead of creating a new thread.

So I have a rain-sensor called sensor.weatherflow_precipitation_rate. It outputs a floating number from 0.0 to I dont know 100 ? In order to smooth its value I created a sensor which calculates the average over the last 5 minutes.

   - platform: average
    name: 'Average rainfall Weatherflow'
    duration:
      minutes: 5
    entities:
      - sensor.weatherflow_precipitation_rate

It looks like this in the dashboard:

My goal is to change the color of the average-sensor icon depending on its state. I installed custom-ui from HACS and tried the following code in customize.yaml but the color doesnt change at all.

sensor.average_rainfall_weatherflow:
   templates:
      icon_color: >
         if (state == 0) return 'blue';
         if (state >= 1) return 'green';
         if (state >= 2) return 'yellow';
         if (state >= 4) return 'red';
         return 'blue';

appreciate any help to get this thing working and learn how to get it right

all the best

Andrew