As the amount of files in the _posts directory has been building up (I think this is the 40th post), it is becoming hard to manually find a file in the folder. I thought of dividing the posts into subfolders according to their categories.

├── articles
│   ├── 2023-01-03-advent.markdown
│   └── 2023-05-22-portfolio.markdown
└── journal-cs
│   ├── 2024-01-16-cs-vs-python.markdown
│   ├── 2024-03-04-cs-vs-python.markdown
│   └── 2024-03-30-merge-csproj-file.markdown

I think this is a good approach, but it has a few drawbacks that need to be mitigated with some code. Today I will address the first one: if I adopt this method, the category of a post will “live” in two places, the front matter and the containing directory.

The front matter is the one that really counts from the point of view of how Jekyll reads the files. If I simply create the folders and move the posts, then if someday I want to change the category of a post two actions are needed: to change the front matter, and to move the post from one folder to the other. I don’t like that - the only action should be to simply move the file from one folder to the other, and that should suffice.

So, how do I achieve the category to be red by Jekyll from the directory name instead of the front matter? With a hook:

# _plugins/assign_categories.rb

Jekyll::Hooks.register :posts, :pre_render do |post, payload|

    category = File.basename(File.dirname(post.path))
    if category != "_posts"   ['categories'] = [category]
        puts "Category assigned to post #{['title']}: #{category}"

Update 01-06-2024: as per this post, it looks like it is possible to make categories to be assigned by the containing folder without the need of a hook. I haven’t tested it myself, but maybe it is worth exploring in the future.