5

I have a matrix block that calls a category channel. The categories are nested three levels "deep" at times. I want to select first, second or third level links as needed.

When I use .last(), I can get the full url path to return. When I use .nth(n), I have to specify a value, which automatically limits the link path to that level of "deepness".

What can I do to get the .last() functionality, without using .last()?

Note: .last() will be deprecated going forward in Craft 3 and beyond.


1 Answer 1

7

If you are not going to update your current project to Craft 3 (which will break nearly all your templates and all plugins anyway) you don't need to bother about that message. This is only for Craft 3 and not for Craft 2.

Otherwise looking in the docs might be a good idea. You can do

{% set query = craft.entries().section('news') %}
{% set total = query.count() %}
{% set last = query.nth(total - 1) %}

or

{% set oldest = craft.entries()
    .section('news')
    .inReverse()
    .one() 
%}
4
  • So I am working in Craft 3 already and that link to the docs is very useful. I implemented nth(query.count() - 1) and it worked great. Thank you.
    – TRIM
    Commented Nov 30, 2017 at 1:29
  • That docs link is now dead. This one might be comparable. It also suggests: In most cases you can replace calls to .last() with .inReverse().one()
    – kr37
    Commented Mar 28, 2018 at 6:38
  • @kr37 your link is now dead as well. Any updated? Commented Mar 8, 2020 at 13:33
  • At this point, I'd say go to https://docs.craftcms.com/v3/ and search for inReverse
    – kr37
    Commented Mar 9, 2020 at 14:22

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.