Table of Contents
Shuffling Collections with a Custom Filter in Eleventy
In Eleventy, you can create custom filters to extend the functionality of the templating system. One useful custom filter is a "shuffle" filter that randomizes or shuffles an array of items or collections. Here's how you can implement it:
// Shuffle / randomize array
config.addFilter("shuffle", function(array) {
// Create a copy of the array to avoid modifying the original
let shuffledArray = array.slice();
// Fisher-Yates shuffle algorithm
for (let i = shuffledArray.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffledArray[i], shuffledArray[j]] = [shuffledArray[j], shuffledArray[i]];
}
return shuffledArray;
});
This custom filter uses the a shuffle algorithm to randomly rearrange the elements in the array. It first creates a copy of the original array to avoid modifying it. Then, it iterates through the array from the end to the beginning, swapping each element with a randomly selected element from the remaining unshuffled elements.
To use this custom filter in your Eleventy templates, simply pass your array or collection to the "shuffle" filter like this: {{ myCollection | shuffle }}
.