1

I have a "contact table" SuperTable with columns for Name, Phone, Email, and Website. In the template, I'm displaying the data as a table.

I only want to generate table columns if a column has data. For example, if there are no Phone Numbers included, I don't want a Phone column. If even one row has a phone number, I do want to include that column.

How do I create a conditional to check whether a SuperTable column has data in it?

This might be related to Querying a supertable field.

1

I forget who solved this for me! I think it was Michael van Dorth.

<div class="table-overflow content-row">
    <table class="table {{ table_class }}">

      {# Caption #}
      {% if block.caption %}
        <caption class="caption">{{ block.caption }}</caption>
      {% endif %}

      {# Setup #}
      {% set rows = block.contactTable.all() %}
      {% set phoneRows = 0 %}
      {% set emailRows = 0 %}
      {% set websiteRows = 0 %}

      {% for row in rows %}
        {% if row.phone != '' %}
          {% set phoneRows = phoneRows + 1 %}
        {% endif %}
        {% if row.email != '' %}
          {% set emailRows = emailRows + 1 %}
        {% endif %}
        {% if row.website != '' %}
          {% set websiteRows = websiteRows + 1 %}
        {% endif %}
      {% endfor %}

      {# Headings #}
      <thead class="thead_class">
        <tr>
          <th scope="col">Name</th>
          {% if phoneRows > 0 %}<th scope="col">Phone</th>{% endif %}
          {% if emailRows > 0 %}<th scope="col">Email</th>{% endif %}
          {% if websiteRows > 0 %}<th scope="col">Website</th>{% endif %}
        </tr>
      </thead>

      {# Body #}
      <tbody class="tbody_class">
        {% for row in block.contactTable.all() %}

          <tr>

            <th scope="row">{{ row.contactName }}</th>

            {% if phoneRows > 0 %}
              <td>{% if row.phone|length %}{{ row.phone.link }}{% endif %}</td>
            {% endif %}

            {% if emailRows > 0 %}
              <td>{% if row.email|length %}
                <a class="btn" href="{{ row.email.url }}" aria-label="{{ row.contactName ~ ' email' }}">Email</a>
              {% endif %}</td>
            {% endif %}

            {% if websiteRows > 0 %}
              <td>{% if row.website|length %}
                <a class="btn" href="{{ row.website.url }}" aria-label="{{ row.contactName ~ ' website' }}">Website</a>
              {% endif %}</td>
            {% endif %}

          </tr>

        {% endfor %}
      </tbody>

    </table>
  </div>
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.