{% set wrapper_attr = wrapper_attr|default(create_attribute()) %}
{% set table_responsive_size = table_responsive_size|default('md') %}
{% set table_responsive = table_responsive|default(true) %}
{% set table_striped = table_striped|default(false) %}
{% set caption = caption|default('') %}

{% set table_wrapper_class = [
  table_wrapper_class ? table_wrapper_class,
  (table_responsive ? 'table-responsive-') ~ (table_responsive_size ? table_responsive_size),
] %}

{% set table_class = [
  table_class ? table_class : '',
  'table',
  table_striped ? 'table-striped',
  table_bordered ? 'table-bordered',
  table_hover ? 'table-hover',
  (not with_headers and headers) ? 'col-headers'
] %}

<figure class="{{ table_wrapper_class|join(' ') }}">
  <table {{ wrapper_attr.addClass(table_class) }}>

    {% if caption %}
      <caption>
        {{ caption }}
      </caption>
    {% endif %}

    {% if with_headers %}

      {% if headers %}
        <thead>
        {% for header in headers %}
          <th>
            {{ header|raw }}
          </th>
        {% endfor %}
        </thead>
      {% endif %}

      {% if rows %}
        <tbody>
        {% for row in rows %}
          <tr>
            {% for item in row %}
              {% if item is iterable and item.attributes is defined %}
                <td {{ item.attributes }}>{{ item.data }}</td>
              {% else %}
                <td>
                  {{ item }}
                </td>
              {% endif %}
            {% endfor %}
          </tr>
        {% endfor %}
        </tbody>
      {% endif %}

    {% else %}
      <tbody>
      {% if headers %}
        {% for header in headers %}
          <tr>
            <th scope="row">
              {{ header|raw }}
            </th>
            {% set row_loop_index = loop.index0 %}
            {% for row in rows %}
              <td>
                {{ row[row_loop_index] }}
              </td>
            {% endfor %}
          </tr>
        {% endfor %}
        {# If we don't have headers, use default #}
      {% else %}
        {% if rows %}
          {% for row in rows %}
            <tr>
              {% for item in row %}
                <td>
                  {{ item|raw }}
                </td>
              {% endfor %}
            </tr>
          {% endfor %}
        {% endif %}
      {% endif %}
      </tbody>
    {% endif %}
  </table>
</figure>
