3

I have a structure as follows:

  • Parent 1
    • Child 1
    • Child 2
    • Child 3
  • Parent 2
    • Child 1
    • Child 2
    • Child 3
  • Parent 3
    • Child 1
    • Child 2
    • Child 3 etc...

On my Child entry pages I want to pull out the other child entries under that parent to use as navigation. I think this should be fairly straight forward but I can not find any documentation on it. So far I have the below but this pulls out all level 2 child entries and not just the entries for the specified parent.

Any help much appreciated.

{% for subnav in craft.entries.section('mySection').level(2).find() %}
    <li><a href="{{ subnav.url }}">{{ subnav.title }}</a></li>
{% endfor %}

3 Answers 3

5

Ok I've worked this out from above and adding some other code and now it works as below:

{% set parent = entry.getAncestors().first() %}
{% for subnav in craft.entries.section('mySection').descendantOf(parent).descendantDist('1') %}
    <li><a href="{{ subnav.url }}">{{ subnav.title }}</a></li>
{% endfor %}

Hope this assists someone else.

2

Sometimes you need the same parent/siblings menu from various POVs (parent or children). Here's what I came up with:

{# Parent / Children subnavigation, either from the perspective of the parent or a child #}

{% if entry.level == 1 %}
  {% set parent = entry %}
  {% set children = entry.getDescendants().all() %}
{% elseif entry.level == 2 %}
  {% set parent = entry.getAncestors().one() %}
  {% set children = entry.getSiblings().all() %}
{% endif %}

<h1><a href="{{parent.url}}">{{parent.title}}</a></h1>
<ul>
    {% for child in children %}
    <li><a href="{{child.url}}">{{child.title}}</a></li>
    {% endfor %}
</ul>

I wonder if that's a detour and there's an easier way?

1

For this you should be able to use the getSibling() method which:

"Returns an ElementCriteriaModel object prepped to return the entry’s siblings (if it lives in a Structure section)."

https://docs.craftcms.com/v2/templating/entrymodel.html#getsiblings

{% set siblings = entry.getSiblings().all() %}

<ul>
    {% for page in siblings %}
        <li class="item-contentmenu">
            <a href="{{ page.url }}">{{ page.title }}</a>
        </li>
    {% endfor %}
</ul>
2
  • I've tried this instead of the code below but with no success again the model returns Null for siblings. Any ideas why?
    – Lettie
    Jul 30, 2015 at 11:13
  • could you show how you tried to implement the getSibling()? But to note it wont really improve on the answer you've given.
    – George D
    Jul 30, 2015 at 16:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.