Badge to count lights on (like on the default Overview)

I’ve searched all day to learn how to do this and have found code to use.

What I never see is exactly where to put that code.

Please help - suggested code and where to put it?

Questions/help: chip cards at top of mobile dashboard - doors open count not working properly - Configuration / Frontend - Home Assistant Community

template:
  - sensor:
    - name: "lights on"
      unique_id: lights_on
      icon: mdi:lightbulb-on
      state: "{{ states.light |selectattr('state','eq','on') | rejectattr('entity_id', 'search', 'light.ENTITY_YOU_DO_NOT_WANTED_COUNTED') | rejectattr('entity_id', 'search', 'light.ENTITY_YOU_DO_NOT_WANTED_COUNTED') | map(attribute='entity_id') | list | length}}"

Thank you for your quick reply. I assume I create a ‘sensor template’?
And use that code there?

Assuming so, I attempted to create one and got this message:

‘It appears you may be writing YAML into this template field (saw ‘template:’), which is likely incorrect. This field is intended for templates only (e.g. {{ states(sensor.test) > 0 }} ).’

Use it anyway?

(I’ll be checking back here in the morning, as I must hit the road in about 5 minutes.)

Put that exact code I have above into your configuration.yaml file or whatever yaml file you are using for additional code such as a package file.

Then use a badge or other card on your dashboard to display that state of that sensor entity, sensor.lights_on

Or use the gui: Settings - Helpers - Create helper - Template - Sensor.

Copy the state content from the post above and adjust it to suit your need.

I haven’t tested it.

(And I think “| list | length” can be just “| count”.)

Thank you both. I put the code in my configuration.yaml file and it works great!

Because this is a relatively new install, I’ll need to ‘adjust’ a few entities being counted as lights - not a big deal though.

The badge is exhibiting odd behavior:

One light on:

More than one light on:

I may have figured it out - seems some of my entities are listed twice (new install), and deleting them is solving the problem of those little badges appearing.