variables are useful but aren’t supported by Template entities (like Template Sensor). If variables were supported then we could avoid duplicating long templates and do things like this:
variables on any trigger is resolved after the trigger. Take a moment to read that whole section. This is a relatively new addition. However it still doesn’t work for your exact case but it does work for many cases. Just see the code I wrote above.
You’ve both effectively justified why it would be a great convenience to support variables for a Template Sensor.
The added complexity of conversion to a Trigger-based entity (for an entity that can already be easily implemented without a trigger), just to use trigger variables, negates the convenience aspect of avoiding template duplication.
Converting to a Trigger-based Template Sensor isn’t always possible. Case in point is the example I posted employing a group entity.
I think you’re miss interpreting both of our responses. We are simply pointing out that you can get reusable code right now without needing this WTH. Your WTH is still valid and a good suggestion.
Our responses are simply to let you know that you can somewhat do this right now.
Special emphasis on the word “somewhat” where the additional complexity of the conversion can detract from the convenience of the goal (i.e. avoid duplication; shrink a few templates).
In addition, a trigger variable is specific to the trigger where it’s defined. So if there are multiple triggers, the variable must be defined in each trigger … which runs contrary to the original goal of minimizing template duplication.
TIL trigger variables work in trigger template entities. I thought they only worked in automations for some reason. Guess I have a lot of refactoring work to do now.
Sure but it adds yet more complexity to something that ought to be simple.
It’s somewhat doable but fugly. To avoid template duplication you can convert the entire Template Sensor to a Trigger-based Template Sensor and employ YAML anchors and aliases for its multiple triggers.
Faced with that prospect, it’s currently easier, and probably less verbose, to just duplicate the template …
Oh yeah, I did the same thing when I found out about them. Then I realized I didn’t really need it… yet. We need some other changes to triggers and template entities for template entities to reach their full potential.
Not sure if this would fix an issue I had some time ago when attempting wifi presence detection using dynamic ip addresses, or if the suggested variable trigger would do the trick… Anyways, I’m voting this.