How to provide correct entity id with template?

I still have a bunch of old format templates that I want to change to the new one.

Old template

sensors:
    energy_generation:
      value_template: '{{ "%0.2f"|format(states("sensor.energy_generated") | float/1000) }}'
      friendly_name: "Generated today"
      unit_of_measurement: "kWh"
      icon_template: "mdi:flash"

This old template would create a sensor with entity id: sensor.energy_generation and name: Generated today

If I try to convert it to the new format

- sensor:
    - name: "Generated today"
      unique_id: energy_generation
      unit_of_measurement: "kWh"
      state: '{{ "%0.2f" | format(states("sensor.energy_generated") | float/1000) }}'
      icon: mdi:flash

It keeps setting the entity id sensor.generated_today.
If I put the name to energy_generation if generates an entity id sensor.energy

What am I doing wrong here?

The entity id is always taken from the name.

Use the name to generate the entity id you want:

- sensor:
    - name: "energy_generation"
      unique_id: energy_generation
      unit_of_measurement: "kWh"
      device_class: energy
      state_class: total_increasing # or total if it does not reset or sometimes decreases 
      state: '{{ "%0.2f" | format(states("sensor.energy_generated") | float/1000) }}'
      availability: '{{ has_value("sensor.energy_generated") }}'
      icon: mdi:flash

Then give the sensor a friendly name using manual customisation:

#configuration.yaml
homeassistant:
  customize:
    sensor.energy_generation:
      friendly_name: "Generated today"
1 Like

Thanks @tom_l this works!
Shame the friendly name part is no longer in the template set… not sure if I like the modern configuration :confused:
I see it has more options, but the old format seems more readable?