I’m trying to get a script built. I want to check if a variable exist and include it if it does. Just really struggling to figure out the formatting. Something like
script:
sequence:
target:
entity_id: "{{ entity }}"
{% if variable is defined %}
data: "{{ variable }}"
{% endif %}
It worked the same as your suggestion above. In cases the variable is used it does works as intended but in the situation the variable is not set it’s still sending data: just with a blank value.
hmm… It looks like
default
is a built-in jinja filter, either omit isn’t a built in option (which would make sense), or Home Assistant doesn’t play nice with it, or doesn’t support it. I’m guessing it’s a special Ansible add-on, as it requires the jinja to impact the yaml outside it (and there is also some artifacts I’ve seen that lend to that happening as well).https://jinja.palletsprojects.com/en/latest/templates/#jinja-filters.default
Maybe you can refactor things a bit to only run this sequence when the variable exists?
It looks like there are conditionals that can be added. I’m not sure if this will work for your specific use case or not, but it’s worth looking into if you haven’t already.
https://www.home-assistant.io/docs/scripts/conditions/
When I tried playing with omit in the template editor I got an error about omit being undefined so probably not built in. Bummer because that would be a very elegant solution to this. I’m going to put this down for the night and try picking it back up tomorrow. I really appreciate all the suggestions. Hopefully it will lead me to a solution.
I looked at all the comments after I posted this and saw your full code. The suggestion I put there isn’t as nice as default(omit), but still probably much better than trying to go with this conditional route, which will probably increase code instead of reducing it. I think that should solve your problem. I didn’t really think about building the entire data payload on the fly until seeing your post, but it makes sense as a solution.