A few days ago Katherine asked: in Eleventy, is there a way to generate pages from separate data (like person-a.json, person-b.json, …) instead of single data file with all the data. Right after seeing the question, I wrote up a JS script which reads all JSON files in a specified folder, combines them into an array and passes them as data to Eleventy. I had the feeling I was going against the Eleventy’s grain. Anyway, it worked.
Today, I stumbled upon the solution by Ashur. A solution that is going with the Eleventy’s grain! A reminder for me to RTFM.
I spent some time going through it to understand how it works, and here are my learning notes. You can find the working prototype in this repo.
Loading JSON files as Eleventy Data
Eleventy natively supports loading JSON files as data. The JSON (or JS files) kept within the _data folder (which can be changed through config) will be loaded as data.
Consider these files:
src
└── _data
└── possums
├── possum-01.json
└── possum-02.json …with content
// src/_data/possums/possum-01.json
{
"name": "First Possum",
"age": 1
}// src/_data/possums/possum-02.json
{
"name": "Second Possum",
"age": 2
}
In the template you can access possum as an object with base filenames keys and their content as values.
{
"possum-01": {
"name": "First Possum",
"age": 1
},
"possum-02": {
"name": "Second Possum",
"age": 2
}
} I can generate a list of possums in Nunjucks with:
<ul>
{% for key, value in possums %}
<li>{{ value.name }}</li>
{% endfor %}
</ul>
Creating pages
Eleventy can generate pages from data. Like you have seen earlier, the data from the JSON files are loaded as an object. Eleventy has some tricks under its sleeve for that too!
By default, when paging an object in Eleventy it provides each key as the value. Using pagination front matter resolve: values, Eleventy provides each value without having to use object[key] to get the value.
---
pagination:
data: possums
alias: possum
resolve: values # 🪄 Iterates over values, instead of keys
size: 1
permalink: "possums/{{ possum.name | slugify }}/"
---{{ possum.name }} is {{ possum.age }} years old
If JSON is not your thing, you can use YAML, TOML or any other data format for maintaining data with Eleventy.