2

I'm struggling to get my head around the syntax to output information in a correct HTML structure. At the moment I have this:

{% for block in entry.menuBuilder %}
{% switch block.type %}
{% case 'menuItem' %}

<ul>
  <li>
    <h2>{{ block.dishName }}</h2>
    <p>{{ block.dishDescription }}</p>
    <p>{{ block.dishPrice }}</p>
  </li>
</ul>

{% case 'subHeading' %}

<header>
  <h2>{{ block.heading }}</h2>
</header>

{% endswitch %}
{% endfor %}

This code is working in that it's displaying the information for me but unfortunately it opens and closes the UL for every item so I end up with:

<ul>
  <li>
    <h2>Name</h2>
    <p>Description</p>
    <p>Price</p>
  </li>
</ul>

<ul>
  <li>
    <h2>Name</h2>
    <p>Description</p>
    <p>Price</p>
  </li>
</ul>

<ul>
  <li>
    <h2>Name</h2>
    <p>Description</p>
    <p>Price</p>
  </li>
</ul> ... etc

What I need to achieve the UL to open, loop through all instances of the Block using just the LI and then close:

 <ul>
  <li>
    <h2>Name</h2>
    <p>Description</p>
    <p>Price</p>
  </li>
  <li>
    <h2>Name</h2>
    <p>Description</p>
    <p>Price</p>
  </li>
  <li>
    <h2>Name</h2>
    <p>Description</p>
    <p>Price</p>
  </li>
</ul>

I've tried adding a for-loop around the LI but I just get errors or nothing at all.

Hopefully this will be simple to somebody!? :D

Many thanks blocks

1 Answer 1

2

You'll want to implement something like this:

{% for block in entry.menuBuilder %}

  {% set type = block.type.handle %}
  {% set isFirstConsecutiveBlockOfType = (loop.first or type != block.getPrev().type.handle) %}
  {% set isLastConsecutiveBlockOfType = (loop.last or type != block.getNext().type.handle) %}

  {% switch block.type %}
  {% case 'menuItem' %}

    {% if isFirstConsecutiveBlockOfType %}
      <ul>
    {% endif %}

      <li>
        <h2>{{ block.dishName }}</h2>
        <p>{{ block.dishDescription }}</p>
        <p>{{ block.dishPrice }}</p>
      </li>

    {% if isLastConsecutiveBlockOfType %}
      </ul>
    {% endif %}

  {% case 'subHeading' %}

    <header>
      <h2>{{ block.heading }}</h2>
    </header>

  {% endswitch %}
{% endfor %}

Basically, for each block we're checking if it is the first or last item in the loop, or if that block's type doesn't match the previous or next block's type. This will let us know if the block we're dealing with is the first or the last in a series of menuItem blocks. Then in the switch/case we can use our new variables to conditionally include any wrapping html.

2
  • Brilliant! Works perfectly thank you!
    – Martin
    Commented May 21, 2019 at 11:52
  • You're welcome, glad it worked! Cheers 🙌
    – Jalen Davenport
    Commented May 21, 2019 at 12:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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