Creating a menu
Creating a menu with previous and next links.
Sorting a collection
There are many ways to sort a collection of posts, some of them provided out-of-the-box by Eleventy see Eleventy#sorting documentation page. . However, 11ty Tips doesn’t use the formated date front matter property but a specific one, named rank_n
it’s an integer positive number , allowing to sort a posts collection according a unique value regardless of the date you could have multiple posts with the same date, unless you use a full date with hours, minutes and seconds… This rank_n
should therefore be a unique index because it is used to retrieve the previous and next pages of any given post in the menu list; however, a duplicate rank_n
index doesn’t cause any disturbance when retrieving those links (see infra). .
11tyTips/source/make/11ty/collections.js
Prism
Listing posts as an HTML fragment
To display the global menu in every page of the site, an HTML fragment is built with a template listing all pages as links in an ordered list, each one having its page rank_n
front matter property recorded as a data-rank
attribute.
The main loop of the menu template iterates thru the posts collection previously sorted and add every useful data that we want to display in the menu itself or as a clue of the previous and next pages: permalink
, rank_n
, title_s
, etc.
11tyTips/source/matrix/menu.njk
Prism
Retrieving posts links in the DOM
Previous and next posts links are much less difficult to retrieve on the client side than at build time. For that reason, the menu template doesn’t try to create a double linked list but instead delegates the work to a JavaScript function run in the browser. For any post page displayed by the browser, we have in the menu HTML fragment built by the template all necessary data about the preceding and following pages relative to the current one when they exist: the first page in the menu list has no previous page and the last one no next page! .
For that we have to search the DOM for the nodes having a data-rank
attribute with values surrounding that one of the current page.
11tyTips/source/matrix/assets/scripts/js/parts/_link_page_.js
Prism
Attaching useful data to links
A link is only a link and doesn’t convey a lot of meaning by itself apart its URL the href
attribute . Unveiling the title and some other pieces of data before fetching a previous or next post is a much more useful help. The data previously retrieved in the surrounding links of the current page are there to be used and we can display them as we like bellow the navigation bar at the top of the page .