1

I want to fill in shuffled images into a CSS grid as a project overview. The images come from a matrix and have 4 different formats. So I want to fill in a format A image into the fitting grid cell (callA1, cellA2 ...). With my code, I have the problem, that the loop iterates over all items and fills all the A-sized cells with the same image. I would like to have image1 in cellA1 and image2 in cellA2 and image3 in cellB1 and so on.

{% for allProjects in craft.entries.section(['projekteZitate']).all() %} 
   {% set shuffledProjects = shuffle(allProjects) %}


       {% for block in shuffledProjects.projekteMatrix %}
                    {% if block.type == 'A' %}
                         {% set image = block.A.one() %}
                             {% if image %}
                              <li class="cellA1"> <img src="{{ image.getUrl() }}"  alt="{{ image.title }}" /> </li>
                              {% endif %}
                    {% endif %} 

                    {% if block.type == 'A' %}
                         {% set image = block.A.one() %}
                             {% if image %}
                              <li class="cellA2"> <img src="{{ image.getUrl() }}"  alt="{{ image.title }}" /></li>
                              {% endif %}
                    {% endif %}

                    {% if block.type == 'B' %}
                         {% set image = block.A.one() %}
                             {% if image %}
                              <li class="cellB1"> <img src="{{ image.getUrl() }}"  alt="{{ image.title }}" /></li>
                              {% endif %}
                    {% endif %}
        {% endfor %}
{% endfor %}
  • You have block.type A twice. Is that on purpose? Also I would look int to the switch syntax. It's more elegant when iterating trough matrix blocks. – KSPR Mar 4 at 9:37
  • Yes, this part of the layout consists of two images of size A and one size B image. They are put in position by the css grid. I would like to have good control of the positions of the image since this is important to the layout of the site. That is why I would like the pick the images one by one and put them in position. – analog junkie Mar 4 at 14:00
2

There is no way to determine if an image should go to the first block.type == 'A' if statement or the second one

you could write something like this:

{% switch block.type %}
    {% case 'A' %}
        {# images for both case a1 + a2. write the loop number into the class name #}
        <li class="cellA{{ loop.index }}"> {# your image #}</li>
    {% case 'B' %}
        {# images for case b #}
        <li class="cellA1"> {# your image #}</li>
{% endswitch %}

That's just one of lots of possibilities

| 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.