Quick help with odd easy template

Im having trouble creating a very basic template sensor off a device tracker attribute. I have a bunch of these in my config but for some reason this guy will not cooperate. Can someone see what im doing wrong?

Ive tried putting ’ around different parts too but no luck…

- platform: template
  sensors:
    q60gas:
      value_template: '{{ states.device_tracker.2019_infiniti_q60.attributes.fuel_level }}'
      friendly_name: 'Q60 Gas'

Invalid config for [sensor.template]: invalid template (TemplateSyntaxError: expected token 'end of print statement', got '_infiniti_q60') for dictionary value @ data['sensors']['q60gas']['value_template']. Got '{{ states.device_tracker.2019_infiniti_q60.attributes.fuel_level }}'. (See /config/sensor.yaml, line 358). Please check the docs at https://home-assistant.io/components/sensor.template/

Try:

- platform: template
  sensors:
    q60gas:
      value_template: "{{ state_attr('device_tracker.2019_infiniti_q60', 'fuel_level') }}"
      friendly_name: 'Q60 Gas'
1 Like

My Man! Thank you sir. That works!..for the future, is there any rules or best practices on when to use it one way vs the other?

It is strongly advised to use the states() , is_state() , state_attr() and is_state_attr() as much as possible, to avoid errors and error message when the entity isn’t ready yet (e.g., during Home Assistant startup).

1 Like

Ah I did not know that. Thanks again, lots of good info.

What @tom_l said, and…

The main problem with your original template was the device tracker’s object ID started with a number. In this case you can’t used states.x.y.z. You’d at least have to write it this way:

 value_template: '{{ states.device_tracker["2019_infiniti_q60"].attributes.fuel_level }}'

See this for more details.

But using the state_attr function is better because it handles errors better.

Intresting, Im glad I posted this. Thank you both, Ive been using home assistant almost 2 years and always struggled with these templates…i feel i have a lot better understanding now. I appreciate you guys taking the time to help!

1 Like