Pass a variable in an entitiy or sensor name

Making a family of person cards. I am using the same code for each family member, but having to update the sensors that are plugged into the code.

Is there a way to use like entity.id in place of the persons name.

Here is a sample of code:

 [[[ 
            if (states["sensor.jim_battery_level"].state > 70) return "#018729"; 
            if (states["sensor.jim_battery_level"].state < 70) {
              if (states["sensor.jim_battery_level"].state > 20) return "#0275f7";
            }
            if (states["sensor.jim_battery_level"].state < 20) return "#EF4F1A";
          ]]]

Iā€™ve seen in some places, where you exit out of the code, maybe html (still learning all this) and plug in $(entity.id).state

so if I used:

 if (states["sensor.${entity.id}%_battery_level"].state < 20) return "#EF4F1A";

That generates an error in the code.

Is this even possible?

If I understand correctly, you try to use variables in lovelace cards ā€¦ You can do that with ā€œcustom:button-cardsā€ by using templates where you can declare variables and assign values to those variables when you place the card in lovelaceā€¦
You can use variables in automations tooā€¦

Could you share more details about the code ?

Here is an example of template cards:

button_card_templates:
    card_network:
        variables:
          icon_on: ""
          icon_off: ""
        color_type: card
        show_label: true
        aspect_ratio: 1/1
        icon: >
            [[[ if (entity.state == "home") return variables.icon_on;
                else return variables.icon_off; ]]]
        styles:
          icon:
            - color: var(--icon-dark-color)
          card:
            - font-size: 12px
            - background-color: >
                  [[[ if (entity.state == "home") return "var(--button-card-background)";
                      else return "var(--automation-card-error)"; ]]]
            - color: var(--icon-dark-color)

and the lovelace card, could be:

- type: custom:button-card
  entity: device_tracker.68_39_43_f8_14_5e
  name: Camera
  label: Salon
  variables:
    icon_on: "mdi:wifi-arrow-left-right"
    icon_off: "mdi:wifi-off"
  template:
    - card_network

You can also extract data injected to variables from entities/helpers like:

  variables:
    var_switch: '[[[ return states["switch.power_air_co_1er_switch"].state]]]'

Please clarify if I misunderstood your questionā€¦

I appreciate all of that, but no. Ultimately, the entity is a person, so the ID is their first name. Because all the sensors are built with their names, if: device_tracker.jim, my hope was that I could use the same code for all the cards, but use the $entity.id in place of the name and identify it at the top of the code.

hopefully that makes more sense.

I think the problem lies with the string for the entity name.

if (states["sensor.${entity.id}%_battery_level"].state < 20) return "#EF4F1A";

I would expect ${entity.id} to be something like ā€œsensor.jim_battery_levelā€, so therefore the string would equate to ā€œsensor.sensor.jim_battery_level%_battery_levelā€, which is obviously not what you want.

However, I suspect that including ā€œ${entity.id}ā€ in a string implies itā€™s a Javascript template literal, which are surrounded by back-ticks rather than quotes:

if (states[`sensor.${entity.id}%_battery_level`].state < 20) return "#EF4F1A";

But once again, you will not get the entity name you want. You would need to pull name out of the entity id along the lines of:

const who = entity.id.split(/[\._]/)[1];
if (states[`sensor.${who}_battery_level`].state < 20) return "#EF4F1A";

if template literals are not supported, you could use the following:

const who = entity.id.split(/[\._]/)[1];
if (states["sensor." + who + "_battery_level"].state < 20) return "#EF4F1A";

I think I understand what youā€™re saying after reading this a few times, but unsure how to implement it.

Ultimately, I have 5 family members, and Iā€™m trying to use the same code in a custom:button-card

type: custom:button-card
entity: person.jim_marks
aspect_ratio: 1/1
name: Person
show_entity_picture: true
show_name: false
hold_action:
  action: none
state:
  - value: home
    styles:
      custom_fields:
        icon:
          - border-color: '#3399ff'
  - value: not_home
    styles:
      card:
        - background-color: '#dedede'
      custom_fields:
        icon:
          - border-color: '#EF4F1A'
styles:
  card:
    - background-color: white
    - border-radius: 5%
    - padding: 10px
    - color: gray
    - font-size: 10px
    - text-shadow: 0px 0px 0px black
    - text-transform: capitalize
    - justify-self: end
    - align-self: middle
  grid:
    - grid-template-areas: '"icon status" "n n" "battery proximity" "wifi ss" "sd sd"'
    - grid-template-columns: 2fr 1fr
    - grid-template-rows: 1fr min-content min-content min-content min-content
  name:
    - font-size: 15px
    - align-self: middle
    - justify-self: start
    - padding-bottom: 10px
  custom_fields:
    icon:
      - clip-path: circle()
      - width: 80%
      - pointer-events: none
      - display: grid
      - border: 5px solid
      - border-color: gray
      - border-radius: 300px
      - margin: 0 10% 0 0
      - justify-self: end
      - opacity: 1
    status:
      - align-self: start
      - justify-self: end
      - color: gray
    wifi:
      - padding: 0.5em 0px
      - align-self: middle
      - justify-self: start
      - color: gray
      - '--text-wifi-color-sensor': >-
          [[[ if (states["sensor.jim_wifi_status"].state == 'false') return
          "#aaaaaa"; ]]]
    battery:
      - padding: 0.5em 0px
      - align-self: middle
      - justify-self: start
      - color: grey
      - '--text-color-sensor': |-
          [[[ 
            if (states["sensor.jim_battery_level"].state > 70) return "#018729"; 
            if (states["sensor.jim_battery_level"].state < 70) {
              if (states["sensor.jim_battery_level"].state > 20) return "#0275f7";
            }
            if (states["sensor.jim_battery_level"].state < 20) return "#EF4F1A";
          ]]]
custom_fields:
  icon: >
    [[[ return entity === undefined ? null : `<img
    src="${states[entity.entity_id].attributes.entity_picture}" width="100%">`;
    ]]]
  status: |
    [[[
      if (states['device_tracker.jim_marks'].state !='home') {
        if (states['sensor.jim_driving_state'].state =='True') {
           return `<ha-icon 
             icon="mdi:steering"
           style="width: 20px; height: 20px; color: '#888888';">
            </ha-icon><span> Driving</span><br/><span>{$states['sensor.jim_driving_speed'].state} mph</span>`;
        } 
        if (states['person.jim_marks'].state =='Thalberg Elementary School') {
            return `<ha-icon 
             icon="mdi:school-outline"
           style="width: 20px; height: 20px; color: '#888888';">
           </ha-icon><span> TES</span>`;
        } else {
        return `<ha-icon icon="mdi:home-export-outline"
        style="width: 20px; height: 20px; color: '#888888';">
        </ha-icon><span> Away</span>`;
        } 
      }
      if (states['device_tracker.jim_marks'].state =='home') { 
      return `<ha-icon 
        icon="mdi:home"
        style="width: 20px; height: 20px; color: 888888;">
        </ha-icon><span> ${entity.state}</span>`;
      } else {
      return `<ha-icon 
        icon="mdi:map-marker-radius"
        style="width: 20px; height: 20px; color: 888888;">
        </ha-icon><span> ${entity.state}</span>`;
      }
    ]]]
  battery: |
    [[[
      if (states['sensor.jim_battery_charging'].state =='true') { 
        return `<ha-icon
        icon="mdi:battery-charging"
        style="width: 20px; height: 20px; color: green;">
        </ha-icon> <span><span style="color: var(--text-color-sensor);">${states['sensor.jim_battery_level'].state}% battery</span></span>`;
      } else {
        return `<ha-icon
        icon="mdi:battery"
        style="width: 20px; height: 20px; color: grey;">
        </ha-icon> <span><span style="color: var(--text-color-sensor);">${states['sensor.jim_battery_level'].state}% battery</span></span>`;
      }
    ]]]
  wifi: |
    [[[
      if (states['sensor.jim_wifi_status'].state =='false') { 
        return `<ha-icon
        icon="mdi:wifi"
        style="width: 20px; height: 20px; color: var(--text-wifi-color-sensor);">
        </ha-icon> <span><span style="color: var(--text-wifi-color-sensor);">Off</span></span>`; 
      } else {
        return `<ha-icon
        icon="mdi:wifi"
        style="width: 20px; height: 20px; color: #888888;">
        </ha-icon> <span><span style="color: var(--text-color-sensor);">On</span></span>`;
      }
    ]]]

Over and over again without having to plug in all the different sensors for each user.

I like the thought of template: -card_network and plugging in all the user information above, but Iā€™m thinking that I have to somehow build all the code into the top and then call the template down below.

How do I call multiple cards here?

Thanks in advance!

You have first to create a template card in ui-lovelace.yaml like this (I used one of mine (which is pretty complex) as I cannot test yours on my system but you can use yours as is (with the correct indentation) and start to add/play with variables step by step):

button_card_templates:

    airco:
        variables:
          var_path: ""
          var_switch: ""
          var_state: ""
          var_antigel: ""
          var_current_temperature: ""
          var_temperature: ""
          var_fan_mode: ""
          var_swing_mode: ""
        icon: >
          [[[ if (entity.state == "off") return "mdi:power-plug-off"; 
              else if ((variables.var_antigel) == "Antigel") return "mdi:snowflake";
              else if (entity.state == "heat") return "mdi:weather-sunny"; 
              else if (entity.state == "cool") return "mdi:snowflake";
              else if (entity.state == "fan_only") return "mdi:fan";
              else if (entity.state == "dry") return "mdi:water";
              else if (entity.state == "heat_cool") return "mdi:brightness-auto";
              else if (entity.state == "unavailable") return "mdi:power-plug-off";
              else return "mdi:help" ; ]]]  
        aspect_ratio: 1/1
        tap_action:
          action: navigate
          navigation_path: '[[[ return variables.var_path]]]' 
        styles:
          card:
            - background-color: 'var(--heater-card-background)'
            - border-radius: 10%
            - padding: 0%
            - color: ivory
            - font-size: 10px
            - text-shadow: 0px 0px 5px black
            - text-transform: capitalize
          grid:
            - grid-template-areas: '"i temp" "i temp2" "n n" "mode mode" "fan fan" "target target"'
            - grid-template-columns: 1fr 1fr
            - grid-template-rows: 1fr 1fr min-content min-content min-content min-content
          name:
            - font-weight: bold
            - font-size: 13px
            - color: white
            - align-self: middle
            - justify-self: start
            - padding-bottom: 2px
            - padding-left: 5px
          img_cell:
            - justify-content: start
            - align-items: start
            - margin: none  
          icon:
            - color: '[[[ if (variables.var_switch == "off") return "var(--heater-card-unknown)";if (entity.state == "off") return "var(--heater-card-off)"; else if (entity.state == "heat") return "var(--heater-card-on)"; else if (entity.state == "cool") return "var(--heater-card-cool)"; else return "var(--heater-card-unknown)" ; ]]]'
            - width: 70%
            - margin-top: 0%
          custom_fields:
            temp:
              - align-self: start
              - justify-self: end
              - padding-right: 10px
              - padding-top: 0px 
              - color: >
                     [[[ if (variables.var_current_temperature < ((variables.var_temperature)-1)) return "var(--button-card-text-under)";
                         else if (variables.var_current_temperature > ((variables.var_temperature)+1)) return "var(--button-card-text-over)";
                         else return "var(--button-card-text-target)" ; ]]]
            temp2:
              - align-self: start
              - justify-self: end
              - padding-right: 10px
              - padding-top: 0px
              - color: >
                     [[[ if (variables.var_current_temperature < ((variables.var_temperature)-1)) return "var(--button-card-text-under)";
                         else if (variables.var_current_temperature > ((variables.var_temperature)+1)) return "var(--button-card-text-over)";
                         else return "var(--button-card-text-target)" ; ]]]
            mode:
              - padding-bottom: 2px
              - padding-left: 0px
              - align-self: middle
              - justify-self: start
            fan:
              - padding-bottom: 2px
              - padding-left: 0px
              - align-self: middle
              - justify-self: start
            target:
              - padding-bottom: 5px
              - align-self: middle
              - justify-self: start
              - padding-left: 0px
        custom_fields:
          temp: >
            [[[
              return `<ha-icon
                icon="mdi:thermometer"
                style="width: 18px; height: 18px; color: yellow;">
                </ha-icon><span> ${variables.var_current_temperature}Ā°C</span>`
            ]]]
          temp2: >
            [[[
              return `<ha-icon
                icon="mdi:bullseye"
                style="width: 18px; height: 18px; color: yellow;">
                </ha-icon><span> ${variables.var_temperature}Ā°C</span>`
            ]]]
          mode: >
            [[[
              return `<ha-icon
                icon="mdi:air-conditioner"
                style="width: 12px; height: 12px; color: yellow;">
                </ha-icon><span> PROG: <span style="color: var(--text-color-sensor);">${variables.var_state}</span></span>`
            ]]]
          fan: >
            [[[
              return `<ha-icon
                icon="mdi:fan"
                style="width: 12px; height: 12px; color: yellow;">
                </ha-icon><span> FAN: <span style="color: var(--text-color-sensor);">${variables.var_fan_mode}</span></span>`
            ]]]
          target: >
            [[[
              return `<ha-icon
                icon="mdi:air-filter"
                style="width: 12px; height: 12px; color: yellow;">
                </ha-icon><span> SWING: <span style="color: var(--text-color-sensor);">${variables.var_swing_mode}</span></span>`
            ]]]

And the card in lovelace is just:

- type: custom:button-card
  entity: 'climate.veranda_c'
  name: "VĆ©randa"
  variables:
    var_path: "/lovelace/airco_courcelles/"
    var_switch: '[[[ return states["switch.airco_veranda"].state]]]'
    var_state: '[[[ return states["sensor.state_airco_courcelles"].state]]]'
    var_antigel: '[[[ return states["sensor.state_chauffage_atelier"].state]]]'
    var_current_temperature: "[[[ if ((states['switch.airco_veranda'].state == 'off') | ((states['switch.airco_veranda'].state == 'on') & (states['climate.veranda_c'].state == 'unavailable'))) return ' - '; else ; return entity.attributes.current_temperature ; ]]]"
    var_temperature: "[[[ if ((states['switch.airco_veranda'].state == 'off') | ((states['switch.airco_veranda'].state == 'on') & (states['climate.veranda_c'].state == 'unavailable'))) return ' - '; else ; return entity.attributes.temperature ; ]]]"
    var_fan_mode: "[[[ if ((states['switch.airco_veranda'].state == 'off') | ((states['switch.airco_veranda'].state == 'on') & (states['climate.veranda_c'].state == 'unavailable'))) return ' - '; else ; return entity.attributes.fan_mode]]]"
    var_swing_mode: "[[[ if ((states['switch.airco_veranda'].state == 'off') | ((states['switch.airco_veranda'].state == 'on') & (states['climate.veranda_c'].state == 'unavailable'))) return ' - '; else ; return entity.attributes.swing_mode]]]"
  template:
    - airco
1 Like

Ok. Still stuck and canā€™t find a lot of information online.

Here is my ui-lovelace.yaml:

button_card_templates:
  about_person_card:
    variables:
      var_wifi_status: ""
      var_battery_level: ""
      var_battery_charging: ""
      var_entity_pic: ""
      var_person_status: ""
      var_driving_status: ""
      var_driving_speed: ""
      var_device_tracker: ""
    icon:
      - clip-path: circle()
      - width: 80%
      - pointer-events: none
      - display: grid
      - border: 5px solid
      - border-color: gray
      - border-radius: 300px
      - margin: 0 10% 0 0
      - padding: 0px 0px
      - justify-self: end
      - opacity: 1
    status:
      - align-self: start
      - justify-self: end
      - color: gray
    wifi:
      - padding: 0.5em 0px
      - align-self: middle
      - justify-self: start
      - color: gray
      - "--text-wifi-color-sensor": >-
          [[[ if (variable.var_wifi_status == 'false') return
          "#aaaaaa"; ]]]
    battery:
      - padding: 10px 0.5em 0px
      - align-self: middle
      - justify-self: start
      - color: gray
      - "--text-color-sensor": |-
          [[[ 
            if (variables.var_battery_level > 70) return "#018729"; 
            if (variables.var_battery_level < 70) {
              if (variables.var_battery_level > 20) return "#0275f7";
            }
            if (variables.var_battery_level < 20) return "#EF4F1A";
          ]]]

custom_fields:
  icon: >
    [[[ return entity === undefined ? null : `<img
    src="${variables.var_entity_pic}" width="100%">`;
    ]]]
  status: |
    [[[
      if (variables.var_entity_status !='home') {
        if (varaibles.var_driving_status =='True') {
            return `<ha-icon 
            icon="mdi:steering"
            style="width: 20px; height: 20px; color: '#888888';">
            </ha-icon><span> Driving</span><br/><span>${variables.var_driving_speed} mph</span>`;
        } 
        if (variables.var_driving_speed > '0') {
            return `<ha-icon 
            icon="mdi:steering"
            style="width: 20px; height: 20px; color: '#888888';">
            </ha-icon><span> Driving</span><br/><span>${variables.var_driving_speed} mph</span>`;
        } 
        if (entity.state =='Thalberg Elementary School') {
            return `<ha-icon 
            icon="mdi:school-outline"
            style="width: 20px; height: 20px; color: '#888888';">
            </ha-icon><span> TES</span>`;
        } 
        if (entity.state =='Southington High School') {
            return `<ha-icon 
            icon="mdi:school-outline"
            style="width: 20px; height: 20px; color: '#888888';">
            </ha-icon><span> SHS</span>`;
        } else {
          return `<ha-icon icon="mdi:home-export-outline"
          style="width: 20px; height: 20px; color: '#888888';">
          </ha-icon><span> Away</span>`;
        } 
      }
      if (variables.var_device_tracker =='home') { 
      return `<ha-icon 
        icon="mdi:home"
        style="width: 20px; height: 20px; color: 888888;">
        </ha-icon><span> ${entity.state}</span>`;
      } else {
        return `<ha-icon 
        icon="mdi:map-marker-radius"
        style="width: 20px; height: 20px; color: 888888;">
        </ha-icon><span> ${entity.state}</span>`;
      }
    ]]]
  battery: |
    [[[
      if (variables.var_battery_charging =='true') { 
        return `<ha-icon
        icon="mdi:battery-charging"
        style="width: 20px; height: 20px; color: #888888;">
        </ha-icon> <span><span style="color: var(--text-color-sensor);">${variables.var_battery_level}% battery</span></span>`;
      } else {
        return `<ha-icon
        icon="mdi:battery"
        style="width: 20px; height: 20px; color: #888888;">
        </ha-icon> <span><span style="color: var(--text-color-sensor);">${variables.var_battery_level}% battery</span></span>`;
      }
    ]]]
  wifi: |
    [[[
      if (variables.var_wifi_status: =='false') { 
        return `<ha-icon
        icon="mdi:wifi"
        style="width: 20px; height: 20px; color: var(--text-wifi-color-sensor);">
        </ha-icon> <span><span style="color: var(--text-wifi-color-sensor);">Disconnected</span></span>`; 
      } else {
        return `<ha-icon
        icon="mdi:wifi"
        style="width: 20px; height: 20px; color: #888888;">
        </ha-icon> <span><span style="color: var(--text-color-sensor);">On</span></span>`;
      }
    ]]]

Here is my card:

type: custom:button-card
entity: person.jim_marks
name: Jim
variables:
  var_wifi_status: states["sensor.jim_wifi_status"].state
  var_battery_level: states["sensor.jim_battery_level"].state
  var_battery_charging: states["sensor.jim_battery_charging"].state
  var_entity_pic: states[entity.entity_id].attributes.entity_picture
  var_person_status: states["device_tracker.jim_marks"].state
  var_driving_status: states["sensor.jim_driving_state"].state
  var_driving_speed: states["sensor.jim_driving_speed"].state
  var_device_tracker: states["device_tracker.jim_marks"].state
template: about_person_card

I get this error:

Button-card template ā€˜about_person_cardā€™ is missing!

Iā€™ve restarted, reloaded configurationsā€¦

Iā€™m so lost.

It is a question of indentation ā€¦ Your ā€œcustom_fieldsā€ should be indented to correspond to the definition of the ā€œabout_person_cardā€ā€¦ In your code, custom_fields is indented at the level of ā€œbutton_card_templates:ā€ā€¦ So Home Assistant is lost in your codeā€¦ ā€œCustom-fieldsā€ should be at the same indentation than ā€œvariablesā€, ā€œiconā€ and so onā€¦ So you have to add 4 blanks in front of all lines starting at ā€œcustom_fieldsā€ including this oneā€¦