2

Okay, I want to create a Matrix based layout like this:

| x | x | x |
| x |   y   |
|   y   | x |

X is a 1/3 column and Y is a 2/3 column.

I want to activate the size Y with a lightswitch.

The problem is: If I have | x | x | y | the layout will blow up because there are too many columns so when the column amount is 3/3 I want to create a new row so all is nice and tidy.

How do I solve this?

My idea was to add a number to each column and when the maximum number is reached, there will be a new row.

That code doesn't work. I just want to show the idea.

{% set x = 33.33 %}
{% set y = 66.66 %}

{% for block in entry.this %}
  {% if x + y = 100 %}<div class="row">{% endif %}
    {# content #}
  {% if x + y = 100 %}</div>{% endif %}

{% endfor %}

If I can get all variables and add them up it should be possible. But how do I get the variables from each iteration.

Anybody know what I'm talking about? Other solutions?

2 Answers 2

4

How about we have a matrix, with block types x and y. Then you can test for block type in your loop:

{% for block in entry.this %}
  {% switch block.type %}
  {% case 'x' %}
    ...
  {% case 'y' %}
    ...
  {% endswitch %}
{% endfor %}

Another issue is that 33.33 + 66.66 = 99.99, which is never going to be equal to 100. (Also, the test for equality is ==: {% if x + y == 100 %}). So let's use x = 1, and y = 2, for a maximum column width of 3. Here's the code:

{% set thisRowLength = 0 %}
{% set thisBlockLength = 0 %}
<div class="row">
  {% for block in entry.this %}

    {# how long is this block? #}
    {% switch block.type %}
    {% case 'x' %}
      {% set thisBlockLength = 1 %}
    {% case 'y' %}
      {% set thisBlockLength = 2 %}
    {% endswitch %}

    {# start a new row if necessary #}
    {% if thisRowLength + thisBlockLength > 3 %}
      </div><div class="row">
      {% thisRowLength = 0 %}
    {% endif %}

    {# now we know it fits, output this block #}
    {{ block.content }}
    {% set thisRowLength = thisRowLength + thisBlockLength %}
  {% endfor %}
</div>

You will end up with an empty <div class="row"></div> if there are no matrix blocks. If that will be a problem, test for it.

2

Instead of building rows, how about building your layout with inline-block elements or flexbox elements with the flex-wrap property set, to make your elements wrap automatically.

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.