Template from string variable

I want to make a template from 2 string concat together.
Has example var1 = 40 and var2 = >80
I want the template to resolve that to var1 + var2 ==> 40>80 ==> false

Example in developer tools template

{% set var1 = "40" %}
{% set var2 = ">80" %}
{% set result = var1 + var2 %}
{{result}}

How can I achieve my goal ?

{% set var1 = 40 %}
{% set var2 = 80 %}
{% set result = var1 > var2 %}
{{ result }}

You haven’t really explained your goal. What you’re asking doesn’t really make sense without context.

Is your snippet an actual template you’re trying to create or an example of what you think you need? Are you in control of those variables? Will they come from sensor values? Is the comparison always >?

String concatenation is done with the ~ operator. You cannot evaluate a string with code in it. It’s generally speaking a huge security risk.

Not it’s not always >.
Those 2 variable come from
var1 an entity state
var2 comme from a customisation on the same entity that it been add when I want an alarm to be tested.
Var2 is like a condition for the trigger of the alarm.
If value is above 80.

If changing the format of var2 isn’t an option you could use an If statement

{% set var1 = "40" | int(0) %}
{% set var2 = ">80" %}
{% if var2 is search(">")%}
{% set result = var1 > var2|replace('>','') | int(0) %}
{% elif var2 is search("<")%}
{% set result = var1 > var2|replace('<','') | int(0) %}
{% endif %}
{{result}}

If you need to cover more comparison methods you could use a dictionary instead:

{% set var1 = "40" | int(0) %}
{% set var2 = "<80" %}
{% set method = var2| regex_findall(find='>=|<=|>|<|==')|first  %}
{% set var2 = var2 | replace(method, '') | int(0) %}
{% set comp = { ">=": var1 >= var2, "<=": var1 <= var2,
">": var1 > var2,"<": var1 < var2,
"==": var1 == var2} %}
{{ comp.get(method) }}
2 Likes

Is this something you create or set?

it’s a customisation in home assistant, i’m adding attribute to and sensor and an automation validate if this condition is true, if so it’s trigger an alarm

OK, but this is all still very abstract and I highly suspect what’s been discussed here is unnecessarily convoluted. What is this alarm? What is your use case here?

1 Like