trouble looping through host list with conditional check and loop.last check to supress seperator on last output

I have a jinja template file that’s iterating through the play hosts and checking which site each hosts belongs to that should output like this:

192.168.1.1, 192.168.1.2, 192.168.1.3,

{%- for host in play_hosts %}{% if hostvars[host][‘site’] == site %}{{ host }}{% if not loop.last %}, {% endif %}{% endif %}{% endfor -%}

However, I’m getting this jinja output instead. It’s not suppressing the separator on the last loop item iteration…

192.168.1.1, 192.168.1.2, 192.168.1.3, 192.168.1.4,

If I remove the if check for the site variable it correctly removes the seperator from the last loop iterate. However, now I have both sites in my output which I don’t want.

{%- for host in play_hosts %}{% if hostvars[host][‘site’] == site %}{{ host }}{% endif %}{% endfor -%}
192.168.1.1, 192.168.1.2, 192.168.1.3, 192.168.1.4, 192.168.2.1, 192.168.2.2, 192.168.2.3, 192.168.2.4

Any Idea’s on how to fix this?

Not tested, but something like this should work

{% set div = joiner(", ") %}
{% for host in play_hosts %}
{%- if hostvars[host]['site'] == site %}
{{ div }}{{ host }}
{%- endif %}
{% endfor %}