1

Just working with a Matrix field to create a flexible, 2 column layout. The user can choose to add either an Image or Rich Text field, and position them accordingly with the Position Select field.

To illustrate, one layout might be:

| image | image |
|       |       |
| text  | text  |

But another might be:

| image | text  |
|       |       |
| image | text  |

Now my solution is to first loop through the Matrix field for each possible position option and group fields depending on their position into arrays. ie: leftContent[], rightContent[], etc.

Printing them out is then simple:

<div class="col col-6 mobile-full">
    {% for row in leftContent %}
        {% if row.type == 'image' %}
            <img src="{{ row.image.first().getUrl() }}" />
        {% else %}
            {{ row.text }}
        {% endif %}
    {% endfor %}
</div>

It would certainly make things easier if you could grab fields for x position? I'm aware this is more of a HTML layout issue and should really be left to the template creator to figure out, but just wanted to see if people had come across this.

Hope that makes sense :)

  • possible duplicate of How can I return specific matrix rows based on criteria? – carlcs Nov 6 '14 at 14:08
  • Hey crawf! I think it's not possible to grab only those matrix blocks with that criteria (→ see that other question). But you found a good workaround to separate them using two arrays leftContent[], rightContent[]! – carlcs Nov 6 '14 at 14:14
  • @carlcs I did see that question, and workaround is a little overboard, but works for the moment! – crawf Nov 6 '14 at 20:10
2

If I'm understanding what you've asked correctly (and there's every chance I'm not – it's been a long day), I've got something similar on one of my sites and I'm using the following code:

{% for faq in entry.faq if faq.column == 'Left' %}
    <li>
        <h3>{{ faq.question }}</h3>
        <p>{{ faq.answer }}</p>
    </li>
{% endfor %}

then:

{% for faq in entry.faq if faq.column == 'Right' %}
    <li>
        <h3>{{ faq.question }}</h3>
        <p>{{ faq.answer }}</p>
    </li>
{% endfor %}

In this case 'faq' is the Matrix field and 'faq.column' is the Position Select field.

There are neater ways to do this to avoid the repeated code, but you get the idea.

  • That's actually a pretty elegant solution! Not to mention didn't know you could combine the for and if statements! – crawf Nov 6 '14 at 20:08

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.