Trying to use IF for the first time, error found character '%' that cannot start any token

So I am trying to update my switch so the vacuum cleaner wont empty the bin if it has already done so:

switch:
  - platform: template
    switches:
      stovsuge:
        friendly_name: "Hermann"
        value_template: "{{ is_state('vacuum.hermann', 'cleaning') }}"
        turn_on:
          service: vacuum.start
          data:
            entity_id: vacuum.hermann
        turn_off: 
        {% if is_state('vacuum.hermann', 'cleaning') %}
          service: vacuum.return_to_base
        {% else %}
          service: vacuum.stop
        {% endif %}
          data:
            entity_id: vacuum.hermann
        icon_template: mdi-robot-vacuum-variant

So the error is on the line where the {% if is_state is.

So this switch works great. When I active, it starts the vacuum. When I switch it off, it returns to dock and empties. But if it is already docked and emptied it will still try to empty, creating a lot of sound. So I tried to only make it return to dock if it is cleaning.

But am I using the IF incorrectly?

you’re using if correctly, but the whole template is in the wrong spot. You cannot template fields. You can only template inside a single field. Also, templates can only go inside fields that allow templates. Typically that’s denoted with the word template. In your case, you need to use the service_template field and the entire template needs to go under that field. Also, you need to let the field know it’s a multi-line template using the multi-line template identifier (>). Lastly, templates need to be indented when using multi-line templates.

        turn_off:
          service_template: >
            {% if is_state('vacuum.hermann', 'cleaning') %}
              vacuum.return_to_base
            {% else %}
              vacuum.stop
            {% endif %}
          data:
            entity_id: vacuum.hermann

Ahh, thank you so much, that fixed the errors! I will go and read up on service templates and where to use them as well.

Not much to read up on. They can only be used in place of ‘service’ fields in actions or scripts.