javascriptnunjuckseleventy

how can i use nunjucks to only show posts from the previous 30 days in eleventy?


i have an eleventy project where i want to display posts, using nunjucks, from a particular collection from the previous 30-days (including the current date).

i found this post but i couldn't get it to work. the way it was written was slightly different than the official docs showed here i didn't know how to use the shortcode created in the stack overflow post. just pasting the code as-is didn't work.

i know virtually zero javascript, so this is all a bit over my head. thank you for any and all help!


Solution

  • I'd use the Collection API to create a custom collection. Here's an example in .eleventy.js

        // https://stackoverflow.com/a/543152/52160
        function datediff(first, second) {        
            return Math.round((second - first) / (1000 * 60 * 60 * 24));
        }
    
        eleventyConfig.addCollection("recentPosts", function(collectionApi) {
            let now = new Date();
            return collectionApi.getFilteredByTag("posts").filter(function(p) {
                return datediff(p.date, now) <= 30;
            });
        });
    

    It assumes a collection of posts and creates a new collection, recentPosts, that match your criteria. I pushed a copy of this demo to my repo: https://github.com/cfjedimaster/eleventy-demos/tree/master/only30days