Search code examples
apostrophenunjucksapostrophe-cms

Create page navigation in Apostrophe CMS


Trying to create 'nephew' pages for a hover-over primary navigation bar - example website structure:

  • the website has pages A, B, C, D
  • under section A there are pages A1, A2, A3
  • under section B there are pages B1, B2, B3
  • I'm currently on page A

The experience I'm trying to create is this:

a) I have a top navigation showing A, B, C (easy - I've done this)

b) My current page A is highlighted (easy - I've done this)

c) When I HOVER over menu A a list of 'child' pages A1, A2, A3 appears (easy - I've done this)

The thing I can't do is this:

d) Displaying child pages outside the current ancestors - i.e. when I HOVER over menu B a list of 'nephew' pages B1, B2, B3 appears under B

I've used the various Apostrophe loops to do (b) and (c):

{% for ancestor in data.page._ancestors %}

But I've run out of options for the 'nephew' pages - essentially I want to do this:

  • give the code a page name
  • have the code display the equivalent of data.page.title but for the specific page, not the current page (i.e. I'd pass the name of page B to this code for it to generate B1, 2, 3).

Solution

  • As in mentioned in the building navigation tutorial, you can configure Apostrophe to load the children of each ancestor to any depth.

    Since the home page qualifies as an ancestor, loading its children to a depth of 2 gives you what you need:

    modules: {
    
      // ... other configuration ...
    
      'apostrophe-pages': {
        filters: {
          // Grab our ancestor pages, with two levels of subpages
          ancestors: {
            children: {
              depth: 2
            }
          },
          // We might want grandchildren of the current page, too
          children: {
            depth: 2
          }
        }
        // other apostrophe-pages options like `types` ...
      },
    
      // ... other configuration ...
    }
    

    Now you can iterate over data.home._children, and over the ._children of each of those "tab" pages in turn as well, giving you the "nephews" you wanted.

    This works if you're more deeply nested too, because we're loading the children of all ancestors to a depth of 2. Just keep looking for ._children properties where you would hope to see them.