Create breadcrumb links

285 words, 2-minute read

The global tacs.nav value is a nested array of data you can use used to build navigation. Refer to the main menu page for a description.

It is difficult to manage tacs.nav using ${ expressions } alone since you must recurse the object. The following sections describe how to create a breadcrumb function you can use in templates.

Create a function library #

As before, edit the lib/nav.js file and add a new breadcrumb() function:

lib/nav.js excerpt

// breadcrumb navigation
export function breadcrumb( currentPage ) {

  const crumb = [];
  recurseNav( tacs.nav );

  const ret = crumb
    .map(n => `<li>${ n.link && n.index ? `<a href="${ n.link }">` : ''}${ n.menu || n.title }${ n.link && n.index ? '</a>' : ''}</li>`)
    .join('\n');

  return ret ? `<nav class="breadcrumb">\n<ol>\n${ ret }</ol>\n</nav>` : '';

  function recurseNav(nav) {

    let found;

    nav.forEach(n => {

      found = found || currentPage === n.data.link;

      if (!found) {
        found = recurseNav(n.children);
        if (found) crumb.unshift(n.data);
      }

    });

    return found;

  }

}

The library has already been imported into the publican.config.js configuration file and appended to the tacs.fn.nav object so no additional code is required.

Use in templates #

A function named tacs.fn.nav.breadcrumb() is now available to content and templates:

${ tacs.fn.nav.breadcrumb( data.link ) }
<h1>${ data.title }</h1>

Assuming the content structure on the main menu page, the resulting menu HTML when you’re visiting the Article one page is:

<nav class="breadcrumb">
  <ol>
    <li><a href="/news/">News</a></li>
  </ol>
</nav>
<h1>Article one</h1>