Table data id in tablerow loop

Hello everybody, merry Christmas! I’m making a quick fix on my website:

When parsing a page content, I generate a <table> by using the {% tablerow %} loop. The page in question is this one, where I list all of my books from a CSV file. My need is to print an HTML id value in the book’s title cell or the hole <tr> (since in every row there’s a book, it makes sense). Would it be possible to do so? I checked this and this documentation pages on Shopify documentation, but I fear I’d need to use a for loop to implement the feature I need.

Here’s the code I’m using (copied and pasted by Jekyll’s official guide on the topic):

  {% for row in site.data.library %}
    {% if forloop.first %}
    <tr>
      {% for pair in row %}
        <th>{{ pair[0] }}</th>
      {% endfor %}
    </tr>
    {% endif %}
	{% tablerow pair in row %}
      {{ pair[1] }}
    {% endtablerow %}
  {% endfor %}

Thanks in advance for your help.

Happy holidays!
T

1 Like

Hi. Happy holidays.

How do you want to generate the ID? I am going to use the slugify filter below on the first column to convert say Foo Bar into foo-bar

I see two options to deal with adding ID.

You can add a wrapping element on the existing code.

{% for row in site.data.library %}
    {% if forloop.first %}
    <tr>
      {% for pair in row %}
        <th>{{ pair[0] }}</th>
      {% endfor %}
    </tr>
    {% endif %}
    {% tablerow pair in row %}
        <span id="{{ pair[1][0] | slugify }}"
            {{ pair[1] }}
        </span>
    {% endtablerow %}
  {% endfor %}

Or you rewrite with for (since you don’t need any of the tablerow features like the parameters it accepts).

{% for row in site.data.library %}
    {% if forloop.first %}
    <tr>
      {% for pair in row %}
        <th>{{ pair[0] }}</th>
      {% endfor %}
    </tr>
    {% endif %}
    {% for pair in row %}
        <td id="{{ pair[1][0] | slugify }}">
            {{ pair[1] }}
        </td>
    {% endtablerow %}
  {% endfor %}
1 Like

Thanks a lot, @MichaelCurrin . Actually, your solution did not work. I managed to find a correct way:

<h2 id="Library">Library</h2>
<div class="table-container">
<table class="library">

  {% for row in site.data.library %}
    {% if forloop.first %}
      <tr>
        {% for pair in row %}
          <th>{{ pair[0] }}</th>
        {% endfor %}
      </tr>
    {% endif %}
    {% tablerow pair in row %}
      <span id="{{ pair[1] | slugify }}">
          {{ pair[1] }}
      </span>
    {% endtablerow %}
  {% endfor %}

  {% comment %}
  {% for row in site.data.library %}
    {% if forloop.first %}
    <tr>
      {% for pair in row %}
        <th>{{ pair[0] }}</th>
      {% endfor %}
    </tr>
    {% endif %}
	{% tablerow pair in row %}
      {{ pair[1] }}
    {% endtablerow %}
  {% endfor %}
  {% endcomment %}
</table>
</div>

Thanks again!

1 Like