From 9ee65e4703afa5ba689e63f73edd6cd5216a8c55 Mon Sep 17 00:00:00 2001 From: Helen Chong <119173961+helenclx@users.noreply.github.com> Date: Tue, 16 Apr 2024 17:20:34 +0800 Subject: [PATCH] Add content category collection and filter --- eleventy.config.js | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/eleventy.config.js b/eleventy.config.js index 6efb657e..8c24371d 100644 --- a/eleventy.config.js +++ b/eleventy.config.js @@ -89,6 +89,27 @@ module.exports = function (eleventyConfig) { /* This is the part that tells 11ty to swap to our custom config */ eleventyConfig.setLibrary("md", markdownLibrary); + // Add content categories to a collection + eleventyConfig.addCollection("categories", function(collectionApi) { + let categories = new Set(); + let contents = collectionApi.getFilteredByTags('articles', 'posts'); + contents.forEach(p => { + let cats = p.data.categories; + cats.forEach(c => categories.add(c)); + }); + return Array.from(categories).sort(); + }); + + // Filter contents by category + eleventyConfig.addFilter("filterByCategory", function(contents, cat) { + cat = cat.toLowerCase(); + let result = contents.filter(item => { + let cats = item.data.categories.map(c => c.toLowerCase()); + return cats.includes(cat); + }); + return result; + }); + // Filter: Format dates const dateOptions = { year: 'numeric',