I copied the template from here, simplifying it by removing state.
https://community.home-assistant.io/t/controlling-only-lights-that-are-on-within-a-group-or-an-area-with-templating/406191/7?u=ikke-t