Eliminating repeated code

How can I prevent repeated code? For each chromecast in my home, I have code like the below. Seems wasteful to have, except for a few lines like the object and player names, the same exact code repeated over and over.

homeassistant:
#----------------------------------------------------------------
  customize:
    input_text.mmp_living_room:
      friendly_name: Music
      icon: mdi:headphones
      custom_ui_state_card: state-card-mini-media-player
      config:
        player: media_player.cast_livingroom
        buttons:
          - name: Top 40
            icon: mdi:music-note
            script: script.play_radio_top40
          - name: Mix
            icon: mdi:music-note
            script: script.play_radio_mix
          - name: Love
            icon: mdi:music-note
            script: script.play_radio_love
          - name: 70s
            icon: mdi:music-note
            script: script.play_radio_70s
          - name: 80s
            icon: mdi:music-note
            script: script.play_radio_80s
          - name: 90s
            icon: mdi:music-note
            script: script.play_radio_90s
          - name: Top Rock
            icon: mdi:music-note
            script: script.play_radio_hardrock
          - name: Hard Rock
            icon: mdi:music-note
            script: script.play_radio_hardrock
          - name: Hair Bands
            icon: mdi:music-note
            script: script.play_radio_hairbands
          - name: Oldies
            icon: mdi:music-note
            script: script.play_radio_oldies
          - name: Old School
            icon: mdi:music-note
            script: script.play_radio_oldschool
          - name: Comedy
            icon: mdi:music-note
            script: script.play_radio_comedy

input_text:
#----------------------------------------------------------------
  mmp_living_room:
    name: ' '

Put the repeated code in an include file and include it everywhere it needs to be.

But it needs to be modified slightly (in the example above, the name of the chromecast and name of the entity are different for each room).

customize_glob:
  input_text.mmp*:
    icon: mdi:headphones
    friendly_name: Music
    custom_ui_state_card: state-card-mini-media-player
    
customize:
  input_text.mmp_living_room:
    config:
      player: media_player.cast_livingroom
      buttons: !include repeated_buttons.yaml

  input_text.mmp_back_room:
    config:
      player: media_player.cast_back_room
      buttons: !include repeated_buttons.yaml

Etc

(edit) just realised you can repeat friendly_name too, code block edited.

3 Likes

OMG - this is gold! Thank you!

1 Like