1

So I want to get 9 random entries from a section and I do this like so:

{% set artists = craft.entries
  .section('artists')
  .artistImage(':notempty:')
  .with(['artistImage'])
  .orderBy('RAND()')
  .limit(9) %}

Now I want to split these entries into a row of 4 and a row of 5. I am doing this like so:

<div class="flex flex-wrap items-center">
  {% for entry in artists|slice(0, 4) %}
    <figure class="w-1/4 sm:w-100px mb-0 border border-white">
      {% include '_includes/_components/image.twig' with {
        image: entry.artistImage[0],
        alt: 'Artists',
        transform: 'square',
        classes:'w-full',
        sizes:'(min-width:576px), 100px, 25vw',
        widthEnd: 800
      } %}
      {{ entry.title }}
    </figure>
  {% endfor %}
</div>

<div class="flex flex-wrap items-center lg:ml-20">
  {% for entry in artists|slice(4) %}
    <figure class="w-1/5 sm:w-100px mb-0  border border-white">
      {% include '_includes/_components/image.twig' with {
        image: entry.artistImage[0],
        alt: 'Artists',
        transform: 'square',
        classes:'w-full',
        sizes:'(min-width:576px), 100px, 20vw',
        widthEnd: 800
      } %}
      {{ entry.title }}
    </figure>
  {% endfor %}

However, this seems to randomise the each split and sometimes I get duplicate entries in each split.

Ideally, I want to get 9 random items and then keep this order and split this into to separate rows.

How can I achieve this?

  • if you use .all() on the query doesn't that set the order of the array returned so the slice will work on the array rather than the query (which is deprecated behaviour anyway right?)? – billythekid Apr 16 at 11:24
  • 1
    Yes you are correct @billythekid - I had missed off the .all() - still getting used to adding that. – Terry Upton Apr 17 at 8:43
1

One way I have achieved this is like so:

{% for entry in artists %}
  {% if loop.first %}
    <div class="flex flex-wrap items-center">
  {% endif %}
  {% if loop.index == 5 %}
    </div>
    <div class="flex flex-wrap items-center lg:ml-20">
  {% endif %}
  <figure class="w-1/4 sm:w-100px mb-0 border border-white">
    {% include '_includes/_components/image.twig' with {
      image: entry.artistImage[0],
      alt: 'Artists',
      transform: 'square',
      classes:'w-full',
      sizes:'(min-width:576px), 100px, 25vw',
      widthEnd: 800
    } %}
  </figure>
  {% if loop.last %}
    </div>
  {% endif %}
{% endfor %}

But I think this circumvents the issue rather than solves the question.

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.