Trying to change button card style based on entity state attribute

Hi,

So, although I’m a technical person I don’t have any experience with code, I’m more an infrastructure guy. I’ve always wanted to learn “to code” and Home Assistant seems like a good introduction to that since it requires a bit of code here and there… so I was hoping someone might help me accomplish this goal as it will inevitably teach me something.

I have been building a grid card for my living room where I use an Amazon FireTV. I have successfully built buttons to change the source via ADB but the default behaviour seems to be that the buttons think they are on all of the time even if the source is changed to another source so you just end up with all buttons thinking they are on.

I have found that the button card natively supports card_mod and here the card style can be changed

Blockquote
card_mod:
style: |
ha-card {
background-color: {{ ‘#AAFFAA’ if is_state(‘binary_sensor.openclose_4’, ‘on’) else ‘#FFAAAA’ }};
}
Blockquote

This example queries a state but in my case I need to query a state attribute. The state attribute I need to query is “source”

And I have also found some documentation which suggests that if statements can be built using state attributes

What I am not sure about is, can I use this if statement inside the card_mod to adjust the style of the button?

The button card does not natively support card mod. You need card mod for it to work. Secondly, if you’re going to template an entire card style based on state, it would be better to use a different set of cards. The custom:button-card can handle this alone and it’s probably your best bet.

If you have installed Card-Mod, you can call a state attribute, too, e. g.:


card_mod:
  style: >
    ha-card {
    background-color: {{ '#AAFFAA' if is_state_attr('media_player.sony_bravia_tv', 'friendly_name', 'Sony') else '#FFAAAA'}};
    }

In the same way you are able to call other attributes.

And please: Don’t use blockquote for code, it makes it harder to help. Use the </> button instead. :green_heart:

Thanks, I now have this working, for anyone with a FireTV / Android TV this is the exact code

card_mod:
  style: |
    ha-card { 
      background-color: {{ '#66AED9' if is_state_attr('media_player.fire_tv_stick', 'source', 'YouTube (FireTV)') else '#000000' }};
    }```