1

I want to fetch a specific block from a Matrix global then pass it through a macro which returns a response based on the block type. However, if I try to use slice the type doesn't appear to be available to the macro. Has anyone experienced something similar?

eg if I set {% set timelineText = timeline.timeline %} (where first timeinline is my global and second timeline is my Matrix field) then fetch a specific block from the Matrix: {% set period = timelineText|slice(0,1) %} should return the first instance/block from the field. I can then pass this to my macro: {{ _self.doPeriod(period) }}

My macro is

{% macro doPeriod(content) %}
{% switch content.type %}
{% case 'quote' %}
    ...
{% case 'period' %}
    ...
{% endswitch %}    
{% endmacro %}```

But this returns the following error: Key "type" for array with keys "0" does not exist

Any thoughts?

  • To add some more detail, if I dump contents of, eg timelineText|slice(0,1) all the Matrix blocks are returned. However, if I do timelineText.first only the first block is returned. Is slice the right filter in this instance/for this use? – Cole Henley Jan 6 '17 at 16:27
  • Okay, if my initial request just fetches the ids then this works as I can fetch specific blocks via an id() request, eg: {% set timelineIds = timeline.timeline.ids() %}. Then {% set period = timeline.timeline.id(timelineIds[0:1]).first %} with {{ _self.doPeriod(period) }} However, this does mean a new DB request for each block which seems a bit excessive – Cole Henley Jan 6 '17 at 16:55
2

First, you need to import your macro, and not just call {{ _self.doPeriod() }}. From the documentation:

When you define a macro in the template where you are going to use it, you might be tempted to call the macro directly via _self.input() instead of importing it; even if seems to work, this is just a side-effect of the current implementation and it won't work anymore in Twig 2.x.

I always do: {% import _self as self %}

slice returns a sequence - in your case an array with one element, and the key is 0. Your macro is expecting a matrix block, not an array, which is why you get that error.

If you only want the first block, then {% set period = timelineText.first %} and period will be a matrix block. {{ self.doPeriod(period) }} will work.

If you want to call doPeriod on all of the matrix blocks, then:

{% for period in timelineText %}
  ... {{ self.doPeriod(period) }} ...
{% endfor %}

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.