Skip to content

Instantly share code, notes, and snippets.

@fpapado
Last active Mar 28, 2020
Embed
What would you like to do?
Roasters by State
---js
{
pagination: {
// Go over the roaster data
data: "roasters",
// Convert the list of roaster to {[state]: {name: string, roasters: Array<Roaster>}}
// (You could do without the {name, roasters} and only have data, but then the iteration is uglier imo)
before: function(roasters) {
let roastersByState = {};
for (let roaster of roasters) {
let currentState = roaster.state;
// If we have not collected this state, add the {name, roasters} construct under it, and the current roaster
if (roastersByState[currentState] === undefined) {
roastersByState[currentState] = {name: currentState, roasters: [roaster]};
}
// Otherwise, add the roasters to the state's list directly
else {
roastersByState[currentState].roasters = [...roastersByState[currentState].roasters, roaster]
}
}
// For some reason, returning the object did not work when I tried it
// It might be that the before callback only accepts an array in the return?
// Not sure, I might have missed something
return Object.values(roastersByState);
},
// Keep one item (from the transformed collection, see below) per page
size: 1,
resolve: "values",
// A more appropriate name for the data
alias: "stateWithRoasters"
},
// The output path for each item of this pagination
permalink: "/state/{{stateWithRoasters.name | slug }}/index.html"
}
---
{% extends "layouts/default.njk" %}
{% block content %}
<ol>
{%- for roaster in stateWithRoasters.roasters %}
<li>{{ roaster.name }}</li>
{% endfor -%}
</ol>
{% endblock %}
@fpapado

This comment has been minimized.

Copy link
Owner Author

@fpapado fpapado commented Mar 28, 2020

I put this under pages/state/index.njk.
It outputs files under /state/alabama/index.html

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