Using Ternary Operators in Widget Expressions

Hi,

Just a quick note to let you know something I discovered by chance…

It has been established that when you make expressions in widgets using the ternary operator:

condition ? ifTrue : ifFalse

you have to enclose them with quotes because it doesn’t work otherwise:

So the solution would be indeed, adding quotes around the entire expression, which was always a bit clumsy:

image

It turns out the only reason you must do this is because of the spaces around the colon :. That’s because YAML will try to interpret it as another key.

So all these work without quotes around the expression if you accept the lack of spaces around the colon:

image

image

image

So, just letting you know - I would rather see no spaces around the colon instead of the entire expression enclosed in double quotes, I think. The added parentheses (2nd suggestion) can add more clarity.

Cheers,
Yannick

6 Likes

Thanks Yannick! This is a great discovery that can clean up a lot of the widget yaml.

Your efforts are appreciated, as always.

1 Like

Thanks, Justin, your helping folks with those widgets is certainly noticed and appreciated as well!

Thanks for the tip. It makes it much clearer using () not needing quotes. And as a bonus when you type the code the parenthesis go green so you can tell which ones belong to which group.

=((Number.parseFloat(items.FroniusSymoInverter_GridPower.state))<=0)?('f7:sun_max_fill'):('if:mdi:transmission-tower-import')