Optional attributes in data_template?

I’m trying to create a script to control a group of lights: if any of them are on, turn the whole group off, otherwise turn the whole group on. This is my first attempt at it

group_toggle:
  alias: Toggle all lights on or off
  sequence:
    - service_template: >
        {%- set initialstate = states(lightgroup) -%}
        {%- if initialstate == 'on' -%}
          light.turn_off
        {%- else -%}
          light.turn_on
        {%- endif -%}
      data_template:
        entity_id: "{{ lightgroup }}"
        transition: 3
        kelvin: 3000
        brightness: 200

This works to turn the group on, but fails to turn the group off because kelvin and brightness aren’t accepted by the light.turn_off service. So I’ve been trying to work out how to exclude those attributes based on the value of the initialstate variable.

I’ve tried a few variations on just removing the entire attribute like this:

data_template:
  entity_id: "{{ lightgroup }}"
  {%- if initialstate == 'off' -%}
    kelvin: 3000
  {%- endif -%}

but they all resulted in parse errors and the script failing to load. My next attempt was trying to set the attribute to an empty value like this:

data_template:
  entity_id: "{{ lightgroup }}"
  kelvin: >
    {%- if initialstate == 'off' -%}
      3000
    {%- endif -%}

Again, this works fine when the group is being turned on, but when it’s being turned off the validator still complains about the kelvin key being present, even though it’s an empty value.

I’m running out of ideas. Is what I want to do possible here?

I would like to know too as I’m facing the same situation.

yeah, I have the same problem… anyone with a solution?

I’ve been following this thread as well to find a solution, however I’ve eventually use scripts or scenes as a workaround, since these could hold additional data.
Based on the light entity state you could trigger a different script/scene, where one includes the brightness/color and other doesn’t.
I’m afk atm, but can post an example I use later.

yes, thats most reliable, keeping logic and specific lights action apart. call the scene from this automation, and set whatever lighting setting you would need in the scene. Or, if you’d need additional conditioning, like a lux-sensor, or sun setting (only st lights on when there is no outside light or the sun is down), write an intermediate script doing that. Works just fine, and keeps the files and automations nice short and simple, and most of all, adaptable to later needs.