2

I am pretty new to craft (just came from EE) and trying to output the last entry from a matrix field in my template:

{% for block in entry.gallery.last() %}
    {% set image = block.image.first() %}
    <img class="lazy" src="{{ siteUrl }}img/assets/loader.gif" data-src="{{ image.getUrl('galleryThumb') }}" data-src-retina="{{ image.getUrl('galleryThumbRetina') }}" alt="{{ image.title }}">
{% endfor %}

So this isn't working as I thought, i've done some snooping but have had no luck, any ideas?

Thanks -Graham

| improve this question | | | | |
0

Untested, but this should work.

You can get the number of matrix blocks in the matrix field by using the Twig length filter like this (see Matrix documentation - scroll to the end):

{% set numberOfBlocks = entry.gallery | length %}

You should then be able to get the last block by directly referencing it like this (since the array of matrix blocks is zero-based):

{% set lastBlock = entry.gallery[numberOfBlocks - 1] %}

Now you have the last block, accessing the image field should work as you had in your original code:

{% set image = lastBlock.image.first() %}
<img class="lazy" src="{{ siteUrl }}img/assets/loader.gif" data-src="{{ image.getUrl('galleryThumb') }}" data-src-retina="{{ image.getUrl('galleryThumbRetina') }}" alt="{{ image.title }}">
| improve this answer | | | | |
  • Excellent work Steve! I am exceptionally pleased with this answer due to the removal of the for loop, much cleaner. – Graham Winston Jul 2 '15 at 10:33
  • To be fair, Alec's answer is better than mine. I had forgotten about Twig's last filter! – Steve Rowling Jul 2 '15 at 15:08
4

Twig comes with a last filter which you should be able to use, so with your entry.gallery you can do:

{% set lastBlock = entry.gallery|last %}

Which will return the last element in the sequence, there's more info in the twig docs:

The last filter returns the last "element" of a sequence, a mapping, or a string:

Twig last filter

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