Tips to DRY up the code?

Hello,

I’m still quite new to HASS and learning my way around all the terminology and tricks.
I find myself repeating a lot of YAML config in my lovelace dashboards - is there anyway I can DRY this up a bit (I have a long list of shortcuts to my favourite playlists for my sonos gear).

Note two things that get repeated a lot:

  1. button-card config - like hide the name, set some styles, etc
  2. the entity_ids
type: horizontal-stack
cards:
  - type: 'custom:button-card'
    name: Ibiza Playlist
    show_entity_picture: true
    show_name: false
    aspect_ratio: 1/1
    entity_picture: /local/playlists/cafedelmar.jpg
    styles:
      card:
        - padding: 0
      entity_picture:
        - width: 100%
    tap_action:
      action: call-service
      service: media_player.play_media
      service_data:
        media_content_id: 'https://open.spotify.com/...'
        media_content_type: music
        entity_id:
          - media_player.office
          - media_player.lounge
  - type: 'custom:button-card'
    name: Glitterbox
    aspect_ratio: 1/1
    show_entity_picture: true
    show_name: false
    entity_picture: /local/playlists/glitterbox.jpg
    styles:
      card:
        - padding: 0
      entity_picture:
        - width: 100%
    tap_action:
      action: call-service
      service: media_extractor.play_media
      service_data:
        media_content_id: 'https://soundcloud.com/...'
        media_content_type: music
      target:
        entity_id:
          - media_player.office
          - media_player.lounge
  ...

Thanks in advance

If you install the lovelace_gen extension, it brings jinja2 template processing to the lovelace configuration. Take a look at Fun with lovelace_gen and jinja2 macros to avoid whitespace indentation problems and see if that could be helpful.

As a practical matter, the jinja2 templating confuses most editors that are trying to validate YAML file contents. Also, you may need to refresh browsers as occasionally the lovelace files are parsed before the extension gets loaded and the jinja2 leaks through to the YAML parser and throws errors at start-up. I use the browser_mod extension to remotely refresh browsers that have Home Assistant pages up.

1 Like

The button card supports templates. You can reduce your button card configuration considerably with these.

For the rest of your config, look up “yaml anchors”.

1 Like

YAML anchors for the win!
Thanks @tom_l!

I still need to get my head around how templates play a role in this scenario, but I’ll get there.

@tom_l question: When I use YAML anchors and save the script/card/other HA thing, the anchors are expressed and written into the saved YAML, so next time I edit, I have to make repeated changes, etc

Is there some way of preventing that from happening? :man_shrugging::crossed_fingers: