Templating - test a for loop

Hi all,
Relatively new but have spent 4 hours searching and trying to get the output I want however no success.

I am trying to build a template to use as a trigger for the miflora sensors when a plant drops below minimum water level. I’m currently using a script I found on here but it is triggering the automation regardless of whether something needs attention.

So far I have the following code:

{% for state in states.plant %}
{{ state_attr(state.entity_id, 'problem') }}
{% endfor %}

Which does what I want - cycles through all my plants and prints the problem like so:

none
conductivity low
conductivity low
moisture low, conductivity low
none
conductivity low

What I’m trying to do is have the output return “true” if “moisture low” shows up anywhere in that output, regardless of how many times it appears. I’ve tried embedding an if statement in the for loop, it changes it to true but subsequent loops will change it back to false so that won’t work.

Has anyone got a simple, short piece of code that will do what I’m after?

B

Share your code once you are at your machine. It’s probably easier to use a combo of rejectattr/count/expand, but we can’t know without knowing the code.

Burningstone is probably right that there is an easier way, but my solution with a for loop looks like this:

{%- set data = namespace(res=false) -%}
{% for e in state_attr('group.todos', 'entity_id') %}
  {% if state_attr(e, 'tbd') %}
	{%- set data.res = true -%}
  {% endif %}
{%- endfor -%}
{{data.res}}

It returns true if any of my entities in the todo group has the tbd flag set. The trick is the namespace part, I think you can adapt this easily to your situation…

Thanks for the replies. I’ve updated my original post in more detail with what I want to achieve.

Then the solution with the for loop should be sth like this:

{%- set data = namespace(res=false) -%}
{% for state in states.plant %}
  {% if 'moisture low' in state_attr(state.entity_id, 'problem') %}
	{%- set data.res = true -%}
  {% endif %}
{%- endfor -%}
{{data.res}}
1 Like