11ty / eleventy-base-blog

A starter repository for a blog web site using the Eleventy static site generator.
https://demo-base-blog.11ty.dev/
MIT License
1.26k stars 623 forks source link

Sorting blog posts in the `content/blog` subfolder #196

Open verlok opened 3 days ago

verlok commented 3 days ago

My content folder has a blog subfolder, which in turn has all the blog posts as subfolders, e.g. how-to-use-this-for-that, and every blog folder contains an index.md file for the post content, plus images that are required for that blog post.

The problem I have is to be able to determine which blog post is more recent and what is older in the content/blog subfolder. I would like a solution where every folder started with the date, e.g. 2024-11-11_how-to-use-this-for-that.

How can I achieve that using eleventy v2? And with v3?

verlok commented 3 days ago

I was able to do so by changing what blog.11tydata.js exports in the content/blog folder

const getFolderName = (data) => {
    const path = data.page.filePathStem;
    const parts = path.split("/");
    const folderName = parts[parts.length - 2];
    return folderName;
};

module.exports = {
    tags: ["posts"],
    layout: "layouts/post.njk",
    eleventyComputed: {
        // Compute the `date` property for each post
        date: (data) => {
            const folderName = getFolderName(data);
            const datePart = folderName.split("_")[0]; // 'YYYY-MM-DD'
            const [year, month, day] = datePart.split("-").map(Number);
            return new Date(year, month - 1, day);
        },
        // Compute the `permalink` property for each post
        permalink: (data) => {
            const folderName = getFolderName(data);
            // Remove the date part from the folder name
            const slug = folderName.split("_").slice(1).join("_");
            // Construct the permalink
            return `/blog/${slug}/`;
        },
    },
};

And I used a Python script made with ChatGPT to rename all the folders using dates from the blog posts frontmatter :)

What do you think? Could it be a good idea to implement this in the eleventy-base-blog repo?

verlok commented 3 days ago

I applied that to my blog, which is maintained at this GitHub repository, and deployed to this domain.