Concatenate sensor values and adding text in a template sensor

Been trying to create a template sensor that holds a string based in the input from other sensors:

  - platform: template
    sensors:
      alarm_summary:
        friendly_name: 'Alarm summary' 
        value_template: > 
          'Alarm {{ states.sensor.alarm_state }} by {{ states.sensor.alarm_changed_by }} the {{ states.sensor.alarm_changed_when }} with a {{ states.sensor.alarm_changed_with }}.'

The expected out put is a string with the following text: Alarm disarmed by Martin the 2019-12-19 15:30 with a tag.

The code above do not work, but do not generate an error. The sensor just states “unkwown”.

change your template to:

        value_template: > 
          Alarm {{ states('sensor.alarm_state') }} by {{ states('sensor.alarm_changed_by') }} the {{ states('sensor.alarm_changed_when') }} with a {{ states('sensor.alarm_changed_with') }}.

or

        value_template: > 
          Alarm {{ states.sensor.alarm_state.state }} by {{ states.sensor.alarm_changed_by.state }} the {{ states.sensor.alarm_changed_when.state }} with a {{ states.sensor.alarm_changed_with.state }}.

Things that you were doing wrong:

  1. Accessing state object’s state incorrectly. Use the state method or state object state directly: states('sensor.xxx') or states.sensor.xx.state.
  2. You’re using a multiline template, but treating it like a single line with your quoting. If you want to make a single line template, wrap it in quotes. If you want a multi-line template, use the >.

single line examples:

value_template: "{{ blah }}"
value_template: '{{ blah }}'
value_tempate: "{{ states('sensor.blah') }}"  #Notice inside and outside quotes
value_tempate: '{{ states("sensor.blah") }}'  #Notice inside and outside quotes

multi line:

value_template: >
  {{ blah }}

and just for clarification

  State Object    State from state object.
  _____________     _
 /             \   / \
/               \ /   \
states.sensor.xxx.state
       \    / \ /
        \  /   \____
       Domain  +   Object_id = Entity_id
          
10 Likes

Someone has experience with ASCII art I see :wink:

1 Like

Thanks, that did the trick.
And thanks for the great explanation with examples and all. :clap: :+1:

haha, not really. It took some extra time getting that done. Preview is a must