
{{ errors }}
{% if errors and not fields %}
  <p>{% for field in hidden_fields %}{{ field }}{% endfor %}</p>
{% endif %}
{% for group, fields in form.fields_by_group %}
  <div {% if group.maskable %}class="maskable_group"{% endif %} id="group_{{ group.id }}">
    {% if group.maskable %}
    <input
      class="toggle_body" 
      type="checkbox" 
      id="maskable_group_{{ group.id }}" 
      name="group_{{ group.id }}"
      {% if not group.default_masked %}checked{% endif %}
      ><label for="maskable_group_{{ group.id }}">{{ group.label }}</label>
    {% endif %}
    <div class="error_group">
      {% for field in fields %}
      <div id="error_{{ field.auto_id }}">
        {{ field.errors }}
      </div>
      {% endfor %}
    </div>
    <div class="body_group">
      {% for field in fields %}
      <div id="div_{{ field.auto_id }}">
        <div{% with classes=field.css_classes %}{% if classes %} class="{{ classes }}"{% endif %}{% endwith %}>
          {% if field.label %}{{ field.label_tag }}{% endif %}
          {{ field }}
          {% if field.help_text %}
            <span class="helptext"{% if field.auto_id %} id="{{ field.auto_id }}_helptext"{% endif %}>{{ field.help_text|safe }}</span>
          {% endif %}
        </div>
      </div>
    {% endfor %}
    </div>
  </div>
{% endfor %}
{% if not errors %}
  {% for field in hidden_fields %}{{ field }}{% endfor %}
{% endif %}
<script>
  const maskables = document.querySelectorAll('.maskable_group');
  maskables.forEach(function (item) {
    if (!item.checked) {
      item.querySelector('.body_group').classList.add('closed');
    }
    console.log('item ' + item);

    item.querySelector('.toggle_body').addEventListener('change', (event) => {
      if (event.currentTarget.checked) {
        item.querySelector('.body_group').classList.remove('closed');
      } else {
        item.querySelector('.body_group').classList.add('closed');
      }
    })

    window.addEventListener('load', function(event) {
      if (item.querySelector('.toggle_body').checked) {
        item.querySelector('.body_group').classList.remove('closed');
      }
      else {
        item.querySelector('.body_group').classList.add('closed');
      }
    });
  })
</script>