1

I have a site which has multiple menus e.g. primary and utility. I've built the menus via sections and the entry type for those sections has a title and a entry field.

This site requires me to show a secondary nav which shows the top level page and it's children as well as highlighting the current page.

I've written this below which works but seem overly complicated for what I'm trying to achieve, being new to Craft I was hoping someone could check this is ok.

The site structure is similar to this: - home - page 1 -- child page 1 -- child page 2 - page 2

Now say I was on page 1, I need to display the following: Page 1 - Child Page 1 - Child Page 2 The same applies if I was on Child Page 1.

What I have currently:

{% set showNav = false %}
{% set entryInNavigation = craft.entries.section(['primaryNavigation', 'utilityNavigation']).relatedTo(entry).one() %}
{% if entryInNavigation %}
    {% set hasDescendants = entryInNavigation.getDescendants().with('relatedEntry').all() %}
    {% if hasDescendants|length %}
        {% set showNav = true %}
    {% else %}
        {% set getParentsChildren = entryInNavigation.parent().children.with('relatedEntry').all() %}
        {% if getParentsChildren|length %}
            {% set showNav = true %}
        {% endif %}
    {% endif %}
{% else %}
    {% set showNav = false %}
{% endif %}

{% if showNav %}
    <ul class="secondary-nav">
    {% if hasDescendants|length %}
        {% for entryInNav in hasDescendants %}
            <li class="secondary-nav__item"><a class="secondary-nav__link {% if entryInNav.relatedEntry[0].id == entry.id %}secondary-nav__link--active{% endif %}" href="{{ entryInNav.relatedEntry[0].url }}">{{ entryInNav.title }}</a></li>
        {% endfor %}
    {% else %}
        {% if getParentsChildren|length %}
            {% for entryInNav in getParentsChildren %}
                <li class="secondary-nav__item"><a class="secondary-nav__link {% if entryInNav.relatedEntry[0].id == entry.id %}secondary-nav__link--active{% endif %}" href="{{ entryInNav.relatedEntry[0].url }}">{{ entryInNav.title }}</a></li>
            {% endfor %}
        {% endif %}
    {% endif %}
    </ul>
{% endif %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.