Mqtt trigger.payload

Can anyone help with this syntax?

What is wrong with this line?

brightness_pct: “{% if trigger.payload > 100 %} 100 {% else %} trigger.payload {% endif %}”

I have also tried

brightness_pct: “{% if trigger.payload > 100 %} 100 {% else %} {{trigger.payload}} {% endif %}”

There is no error on a configuration test, but neither example will set the appropriate brightness. I try to use the template work area to test, but trigger.payload is not recognized and adding variables doesnt prove anything because the test area can set an actual brightness.

Thanks

The received payload is (probably) a string so it must first be converted to a numeric value (integer or float) before performing a numeric comparison.

brightness_pct: "{% if trigger.payload | int > 100 %} 100 {% else %} trigger.payload {% endif %}"

You can use inline if-else to create a more compact version of the template:

brightness_pct: "{{ 100 if trigger.payload | int > 100 else trigger.payload }}"

That was exactly it! Thank you very much!

Just curious, when do you have to use ‘{{’ or ‘{’?

{{ }} is for output
{% %} is for everything else: setting variables, logic, etc.

Anything not in either is literal.

2 Likes

It’s all described in the first section of the documentation for the Jinja template engine: Synopsis

From the documentation:

There are a few kinds of delimiters. The default Jinja delimiters are configured as follows:

Thank you! I appreciate everyone’s time very much.

1 Like

To help other users, with a similar problem, find the solution quickly, please mark my post (above) with the Solution tag. Only you, the author of this topic, can do that. It will automatically place a check-mark next to the topic’s title (indicating it has a proven solution) and will add a link to your first post (to the identified Solution).

what if the payload is numeric value already?
I want to set fan based on the temperature from mqtt sensor. If it is below 16.2 it should trigger: Now I have the conditions this way: {{ trigger.payload | int < 16.2 }} but I feel that the int is not needed when it is already numeric value.

EDIT: because now it triggers even when the temp is 16.6 so it shouldn’t.