Dynamic single category list page based on current category url

I’ve been trying to sort this out for a day or two and looked at a lot of possible solutions, trying combinations of different snippets. After a lot of searching and tests Ive now got a tidy simple solution to using page url to determine a current category page and then call only those posts in that category. This is without using any plugins and works on GitHub pages. I’ll use category ‘Tutorials and Guides’ as my example.

  1. Create a dir for ‘category’ at root
  2. Place individual category .md files in it. Here Ive got ‘tutorials-and-guides.md’
  3. The front matter is:
layout: category
title: Tutorials and Guides
description: posts in the category 'tutorials and guides' 
permalink: category/Tutorials and Guides
exclude: true  
  1. create a category template in _layouts
  2. In the category template place the front matter (you can probably add other stuff but I’m just using this for now).
layout: default
permalink: /category/
  1. And then add the following script
{% assign current_cat = page.url | split: "/" | last %}
{% for post in site.categories[current_cat] %}
    <ul><li><a href="{{ site.baseurl }}{{ post.url }}">{{post.title}}</a></li>  
    {% endfor %} </ul>

This should call the specific category your page url is currently highlighting.

FYI I’m using the ‘current category page’ as the page the user arrives at if they click on categories (or tags) in a post. That script is added to your post template. But, you could use this in other situations like navigation I think.

That’s it. I hope this helps others cos for me it’s the easiest simplest way to make this happen.

1 Like