Jinja double evaluation

So I am trying to keep code compact and I was looking to do the following.

I have a set of sensors with a set of names and corresponding values
Sensor.blueValue 100
Sensor.redvalue 345
Sensor.greenvalue 123

I have the following sensor:
Sensor.currentselectedcolor having value blue, red or green

Finally I have a sensor sensor.currentvalueforcolor which should hold the value of the sensor.Colorvalue corresponding to the current value of sensor.currentselectedcolor

So for example: if sensor.currentselectedcolor is red the sensor.currenvalueforcolor should be 345

I know this can be done through a chain on if then else in a template sensor but I am looking for a more compact solution (if it exists)

I can form the data source entity_id with the following
States.sensor.{{ states.sensor.currentselectedcolor.state}}value.state
But I cannot manage to have this generated literal evaluated once again and assigned to a template sensor sensor.currentvalueforcolor

So. Is there a way to do :
Template:

  • sensor
    Name: currentvalueforcolor
    State: >
    {{ evaluation of(States.sensor.{{ states.sensor.currentselectedcolor.state}}value.state) }}

So by double evaluation I mean first evaluating the inner expression and then evaluating the resulting expression.
In this elegant way I could avoid n subsections of an if then else else endif replacing them with 4 rows

Hope I was clear
Tx for any suggestions

Try this:

state: >
  {% set entity = 'sensor.' ~ states('sensor.currentselectedcolor') ~ 'value' %}
  {{ states(entity) }}
1 Like

Could this be even more compact ?

state: >
{{ states( ‘sensor.’ ~ states(‘sensor.currentselectedcolor’) ~ ‘value’ %)) }}

No. That will generate an error.

states() will pick up the first thing it sees in quotes as the entity id, so it will try this states( 'sensor.' then complain about the rest of the junk it was not expecting to see. You need to create the full entity id then supply it to states().

EDIT: See comments below.

1 Like

I’m not understanding why that wouldn’t work other than the extraneous %) in the middle of it. I frequently use a similar method. Is there something I’m not seeing here?

Nope. I just assumed that would be the case. Perhaps it will work then.

state: "{{ states('sensor.' ~ states('sensor.currentselectedcolor') ~ 'value') }}"
1 Like

Order of operations when executing. Code typically resolves arguments as it hits them. Arguments can contain math, and at that point it follows pemdas order.

1 Like

works . Thanks
I will revise a lot of stuff that was if statement filled.
might be a little less readable but is soooo much more compact