1

Hi all… I have a Structure organized like this:

  1. Arts
    • Journals
      • Submissions
    • Books
  2. Sciences
    • Journals
      • Submissions
    • Books

…etc.

In my template, I want to grab the "Section" (e.g. Arts, Sciences) that I'm in and output it at the top of the page, both on the main page and subpages.

For decedents I can do that using:

    {% set currentSubject = entry.getAncestors().level(1) %}
    {% for entry in currentSubject %}
    {{ entry.title }}
    {% endfor %}

But if I'm on the main page (e.g. Arts, Sciences) itself getAncestors won't help. Is there a smart conditional that will give me the title of the top level page regardless of if I'm on it or a descendent of it?

For some reason, I find myself hoping this can be done without looking at segments, but maybe that's the best route for this kind of thing?

1
  • I usually end up using segments for this, something like {% set topLevel = craft.entries.slug(craft.request.segment(1)).first() %}. Jan 12 '15 at 17:14
1

You can test for the entry's level property. Something like the following.

{% if entry.level == 1 %}
    <h1>{{ entry.title }}</h1>
{% else %}
    <h1>{{ entry.ancestors.first.title }}</h1>
{% endif %}
2
  • Ah, I didn't think about using level — that's a great solution. This is working, though I found that for the tertiary+ level we need "entry.ancestors.**first**.title" to get the right result … editing above.
    – philzelnar
    Jan 12 '15 at 19:44
  • Great! I pulled this out of one of my own projects where the structure was limited to two levels. Couldn't remember whether '.first' or '.last' would get you to the top level. I updated the example to use 'first'. Jan 12 '15 at 19:51

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.