0

I have a matrix field that allows the user to add little 'designed' features throughout the page. These are placed in certain positions on the page and so I want to loop through these but because they are dotted about he page, I cannot do a simple, for loop.

Instead I could get all the blocks like this:

  {% set nuggets = entry.nuggets
    .with([
    'nugget:nuggetBody',
    'nugget:icon'
  ])
    .all() %}

Then I could place them like so:

{% set nugget = nuggets[0] %}
{% include '_includes/_components/nugget.twig' with {
  self: {
    size:'xl',
    bgColor: nugget.circleColour.color[0].class,
    iconPath:nugget.icon[0].path,
    body: nugget.nuggetBody[0].bodyPlain
  }
} %}


{% set nugget = nuggets[1] %}
{% include '_includes/_components/nugget.twig' with {
  self: {
    size:'xl',
    bgColor: nugget.circleColour.color[0].class,
    iconPath:nugget.icon[0].path,
    body: nugget.nuggetBody[0].bodyPlain
  }
} %}

etc etc

I wondered if there is a better or more streamlined way than this? And what happens if they don't have 'enough' blocks, how to accomodate, if for example, I have placed 6 around the page in the design and code, but they only add 4. I know I could do this...

{% if nuggets|length >= 3 %}
  {% set nugget = nuggets[2] %}
  {% include '_includes/_components/nugget.twig' with {
    self: {
      size:'xl',
      bgColor: nugget.circleColour.color[0].class,
      iconPath:nugget.icon[0].path,
      body: nugget.nuggetBody[0].bodyPlain
    }
  } %}
{% endif %}
etc

But is there a better approach...?

0

There is a better approach by which you can change positions from the admin panel. You need to create a matrix where there will be different blocks types, and display them in a loop. enter image description here

{% for block in entry.matrixField.all() %}
   {% switch block.type %}
      {% case 'one' %}
          {{ block.content }}
      {% case 'two' %}
          {{ block.content }}
   {% endswitch %}
{% endfor %}
  • The problem @PavelPavlovich is that I cannot loop them as they are not all output together. As I said in the post, these items are dotted around the design. So I need to inset the first one (at the top) and then in another part of the page insert the 2nd and 3rd one and then a forth one somewhere else. It is not a case of a simple matrix builder and looping all the items. I already use a matrix field to add these items. It is just if there is a better way ot output them when they are not in a single loop. – Terry Upton Nov 13 '20 at 13:45
  • @TerryUpton If you have everything scattered dotted across the page, and all the content of the elements is added in a separate matrix, why don't you change their positions from the admin panel or are you already doing this? – Pavel Pavlovich Nov 15 '20 at 16:23

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.