If and Else in yaml file

Hi there,

new to Home Assistant and the Community. Slowly starting to get familiar with yaml files. I saw this being posted on reddit (https://www.reddit.com/r/homeassistant/comments/mxf4fy/finished_my_lovelace_mobile_dashboard_if_there/) and now I’m trying to change it a bit.

The dashboard only shows the “Home” and “Not Home” categories. However, I also want to know if a device has status Unknown, which changes it into three conditions. I can’t seem to get this working. Any guidance on what I’m doing wrong? The error I’m getting is

ButtonCardJSTemplateError: SyntaxError: Unexpected token ‘else’ in ‘if (states[“device_tracker.iphone”].state == “not_home”) return `<ha-icon ic…’

Thanks in advance!

      - type: 'custom:button-card'
        entity: device_tracker.iphone
        show_entity_picture: true
        entity_picture: /local/pardonny.png
        show_name: true
        name: ParDonny
        show_icon: false
        styles:
          card:
            - padding: 2%
            - height: 145px
          entity_picture:
            - width: 20%
            - top: 4%
            - background-repeat: no-repeat
            - background-position: top center
          custom_fields:
            location:
              - text-transform: capitalize
              - position: absolute
              - left: 4%
              - top: 4%
              - color: >-
                  [[[ if (states["device_tracker.iphone"].state == "not_home")
                  return "#e45649"; else return "#50A14F"; ]]]
        custom_fields:
          location: |
            [[[
            if (states["device_tracker.iphone"].state == "not_home")
                return `<ha-icon
                  icon="mdi:home-export-outline"
                  style="width: 22px; height: 22px;">
                  </ha-icon>`
            elif (states["device_tracker.iphone"].state == "unknown")
                return `<ha-icon
                  icon="mdi:home-alert"
                  style="width: 22px; height: 22px;">
                  </ha-icon>`
            else
                return `<ha-icon
                  icon="mdi:home"
                  style="width: 22px; height: 22px;">
                  </ha-icon>`
            endif
            ]]]

Alas, the error notice is not clear enough. The Java inside custom:button-card does not like

elif

Simply use if instead.

Exactly. The return acts as an “exit” to that particular section of code, so you can just stack if returns and then end with an else return

Ah, right Russell, I forgot: No need for an endif , too.

Jup, that was it. Many thanks for your quick reply’s guys. Problem solved.