Ad

Issue With Forloop.index In Shopify Section

- 1 answer

I am working on a dynamic tab section in Shopify but am facing a problem. I have created two loops, one for a tab's href tag and the second for an associated content element. I need the former to reference the latter, but in my current code the output in href tags shows 1 or 2 but in the tab content they start from 3. Pls help me!

My HTML/Liquid:

<ul class="tabs-nav">
  {%- for block in section.blocks -%}
    {% if block.type == 'tab-title' %}
      <li class="tab-active">
        <a target="_blank" rel="nofollow noreferrer" href="#tab-{{ forloop.index | plus: 1 }}">
          {{ block.settings.serv_title }}
        </a>
      </li>
    {% endif %}
  {%- endfor -%}
</ul>
<div class="tabs-stage">
  {%- for block in section.blocks -%}
    {% if block.type == 'tab-content' %}
      <div id="tab-{{ forloop.index }}" style="display: block;">
        {{ block.settings.serv_cont }}
      </div>
    {% endif %}
  {%- endfor -%}
</div>

My JavaScript:

$('.tabs-nav a').on('click', function (event) {
  event.preventDefault();
  $('.tab-active').removeClass('tab-active');
  $(this).parent().addClass('tab-active');
  $('.tabs-stage div').hide();
  $($(this).attr('href')).show();
});
$('.tabs-nav a:first').trigger('click');
Ad

Answer

The issue I think is in the structure of your settings schema. It sounds like you currently have schema for title blocks and content blocks separately (and that with your current config settings data, you have four blocks total.) You could instead have schema for one block, that contains the associated title and content. Then you would only have to use one for loop (although you would have to capture the title, capture the content, and output each into your HTML separately...

With that said, using your existing code, you can do this (assuming there are always an equal number of title and content blocks in your settings data, and that they are ordered correctly in the drag/drop editor):

<ul class="tabs-nav">
  {%- assign titleIndex = 0 -%}
  {%- for block in section.blocks -%}
    {% if block.type == 'tab-title' %}
      {%- assign titleIndex = 0 | plus: 1 -%}
      <li class="tab-active">
        <a target="_blank" rel="nofollow noreferrer" href="#tab-{{ titleIndex }}">
          {{ block.settings.serv_title }}
        </a>
      </li>
    {% endif %}
  {%- endfor -%}
</ul>
<div class="tabs-stage">
  {%- assign contentIndex = 0 -%}
  {%- for block in section.blocks -%}
    {% if block.type == 'tab-content' %}
      {%- assign contentIndex = 0 | plus: 1 -%}
      <div id="tab-{{ contentIndex }}" style="display: block;">
        {{ block.settings.serv_cont }}
      </div>
    {% endif %}
  {%- endfor -%}
</div>
Ad
source: stackoverflow.com
Ad