Skip to content

Instantly share code, notes, and snippets.

@fpapado
Last active March 28, 2020 19:15
Show Gist options
  • Save fpapado/d3bb821a9598cadc4ad3a4bd7a989cd3 to your computer and use it in GitHub Desktop.
Save fpapado/d3bb821a9598cadc4ad3a4bd7a989cd3 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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