2

I can grab a top/bottom level ancestor with something like entry.ancestors.first/last.title.

But, say I'm at level 6, is it possible to grab an ancestor at a particular level, like entry.ancestors.level(3).title? Or would you have to grab all the ancestors and loop through them to accomplish this?

New to deep structures and just want to confirm I'm not missing something that would allow me to sidestep a loop. Thanks!

3

entry.ancestors returns an ElementCriteriaModel (→ getAncestors() in the Craft docs) prepped to return the entry's ancestors.

entry.ancestors.level(3) makes it return only entry ancestors which are at 3rd level of the structure.

As you well pointed out in the comments, an entry can only have one ancestor on a particular structure level. So you can now use the first() method to get this one entry. Keep in mind that if there's no ancestor at that level, the method won't return anything (null).

{% set ancestorL3 = entry.ancestors.level(3).first() %}

{% if ancestorL3 %}
    {{ ancestorL3.title }}
{% endif %}
  • I see… I was thinking .level(3) would return a single entry as .first does (not sure how an entry could have more than one ancestor at a particular level). Thanks! – philzelnar Feb 4 '15 at 17:34
  • @alsophil male and female?? ...errrm no. – carlcs Feb 4 '15 at 18:12

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.