Templating : how to call a service within loop?

Hi,
I’m trying to call a add note service for new items in my sensor list.

- id: '1574857273192'
  alias: 'Shopping list: Grocy to gkeep'
  description: ''
  trigger:
  - entity_id: sensor.grocy_shopping_list
    platform: state
  condition:
  - condition: template
    value_template: "{% if trigger.from_state.state < trigger.to_state.state %}\n\
      \  True\n{% endif %}\n"
  action:
  - service: gkeep.new_item
    data_template:
      item_title: >-
        {% for new_item in trigger.to_state.attributes['items'] %}
          {% if new_item not in trigger.from_state.attributes['items'] %}
            {{ new_item._product._name }}
          {% endif %}
        {% endfor %}

This code runs only once the service with all new items
I tried with a loop in service (like service_template)

Any idea ? :slight_smile:

Kind regards

Services are single executions. All templates resolve to 1 result.

If you want to do a loop, you need to get inventive with a counter and 2 scripts.

1 Like

Also, your value_template isn’t quite correct for your condition. You need to return a true or false. You can’t just return a true. Simply do this by omitting the if statement and outputing the check itself. But… You’re comparing strings, which doesn’t make sense. Are you trying to compare the length of the string? I think you want this:

  condition:
  - condition: template
    value_template: "{{ trigger.from_state.state | length < trigger.to_state.state | length }}"

Thx for condition. No I’m trying to compare numbers.
No implicit compare ?

I tried with script. But it’s the same. But 2 scripts and a counter seems to be a good idea, thx :+1:

I can do it with app daemon but :wink:

Thx again and keep in touch (I have some tests do because of you :slight_smile: )

Sorry some edits my answer

If you’re comparing numbers you gotta cast them to a number, otherwise 9 > 10 as a string.

  condition:
  - condition: template
    value_template: "{{ trigger.from_state.state | float < trigger.to_state.state | float }}"

That or a python script. I’d probably do a python script if it’s just a single call. But if your conditions get crazy, appdaemon.

1 Like

Python script. Thx :slight_smile:

I did some appdaemon apps but now most of their features are in custom components.

(Appdaemon is very powerful and a good way to learn python)