Skip to content

Instantly share code, notes, and snippets.

@yuigoto
Last active April 19, 2019 23:14
Show Gist options
  • Save yuigoto/af2bd8eaeac5e8123c6c9b1df6a59f4b to your computer and use it in GitHub Desktop.
Save yuigoto/af2bd8eaeac5e8123c6c9b1df6a59f4b to your computer and use it in GitHub Desktop.
[JavaScript : Metalsmith Paginator] : Metalsmith + Handlebars pagination #js
/**
* YX : HANDLEBARS : cleanTrailingHtml
* ----------------------------------------------------------------------
* Clears the trailing `index.html` from path strings.
*
* @author Fabio Y. Goto <lab@yuiti.com.br>
* @copyright 2018 Fabio Y. Goto
* @since 0.0.1
*
* @param {string} string
* String to remove the trailing HTML file from
*/
module.exports = (string) => {
// Remove using REGEX
return string.replace(/\/*index.html$/, "");
};
/**
* YX : HANDLEBARS : compare
* ----------------------------------------------------------------------
* Executes a comparison operation on two values.
*
* @author Fabio Y. Goto <lab@yuiti.com.br>
* @copyright 2018 Fabio Y. Goto
* @since 0.0.1
*
* @param {string} operation
* The type of operation to execute
* @param {*} value1
* Left number to compare
* @param {*} value2
* Right number to compare
*/
module.exports = (operation, value1, value2) => {
switch (operation.trim) {
case "<":
return (value1 < value2);
case ">":
return (value1 > value2);
case ">=":
return (value1 >= value2);
case "<=":
return (value1 <= value2);
case "==":
return (value1 == value2);
case "===":
return (value1 === value2);
}
};
<!--
Since I found it so hard to discover this by myself, I wanted to
make it easy for people using `metalsmith-pagination` to build
pagination for their blogs and other paginated content.
I also placed two helpers for handlebars, which I use to compare
values and render the first/next/previous/last page links.
-->
<ul>
<!-- FIRST / PREVIOUS PAGE -->
{{#if (compare ">" paginators.num 1)}}
<li>
<a href="/{{cleanTrailingHtml paginators.first.path}}">
First Page
</a>
</li>
<li>
<a href="/{{cleanTrailingHtml paginators.previous.path}}">
Previous Page
</a>
</li>
{{/if}}
<!-- NUMERICAL NAVIGATION -->
{{#each (paginators.getPages 3) as |page|}}
<li>
<a href="/{{cleanTrailingHtml page.path}}">
{{page.pagination.num}}
</a>
</li>
{{/each}}
<!-- NEXT / LAST PAGE -->
{{#if (compare "<" paginators.num paginators.next.pagination.num)}}
<li>
<a href="/{{cleanTrailingHtml paginators.next.path}}">
Next Page
</a>
</li>
<li>
<a href="/{{cleanTrailingHtml paginators.last.path}}">
Last Page
</a>
</li>
{{/if}}
</ul>
@yuigoto
Copy link
Author

yuigoto commented Mar 18, 2018

I gotta thank Robert Rüdiger (@ruerob) for the fixes and pointing some optimizations! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment