Check if entity exist in a IF THEN action

Hi All,

Sometimes “Alexa Media Player” have a update that can break the integration.
Can happen, not a big deal. Developer is always fast to solve this.

But i use Alexa Media Player in many automatons. When the entity is not existing then the script stop working.

How can i create a IF ELIF to check entity is exist, if not then do something else?

Cheers,

{% if states.media_player.some_name.state is defined %}
  if it exists actions
{% else %}
  if it doesn't actions
{% endif %}
1 Like

Thank you!

Can you tell me if this is same way but then one 1 line ?

"{{ 'script.engine_say' if states.media_player.peter_s_echo_dot.state is defined else 'script.none' }}"

Developer tool give same result.

looks fine to me.

1 Like

Such a code doesn’t work on my custom:button-card. Here is my code (trying to make an icon color depending on a media player’s state [icon is ‘lime’ when playing; ‘dimgray’ when not playing; invisible - gets background color - when not available]):

icon:
  - color: |
          [[[
            if ("{{ states('media_player.philips_tam8905') is defined }}")
             {
               if (states["media_player.philips_tam8905"].state == 'playing') return 'lime'
               else return 'dimgray'
              }
            else return 'var(--primary-background-color)'
          ]]]

And when my Philips media player becomes unavailable, instead of a nice card I get this:

ButtonCardJSTemplateError: TypeError: states['media_player.philips_tam8905'] is undefined in 'if ("{{ states('media_player.philips_tam8905') is defined }}") { if (states["media_player....'

Seems, the syntax of this card is ok, but it doesn’t work as expected when my Philips disconnects from HA.
Can you, please, give me a hint?
Thank you in advance!

why suddenly [ instead of ( ?

My idea is that the icon of the media_player entity should be always displayed on the custom button-card regardless the availability of its entity. I just want to play with its colors, depending on the availability or various current states of the media player.
When the media player becomes unavailable, the icon’s color shoud be set to var(--primary-background-color) - in fact the icon shouldn’t be visible in this case (it gets the same color as a background) but still should be displayable.
Seems, I’ve shared a self-explanatory code.