Quick Tip: Filtering the Ghost Home Page by Tag

Quick Tip: Filtering the Ghost Home Page by Tag

Do you need to filter your homepage content by a specific tag? If you're thinking of editing the front end handlebars template - don't! There's an easier way :)

I wanted to show only posts with the development tag on the homepage of my blog. My initial approach was to filter the posts loop in the homepage (home.hbs) template:

{{#get "posts" limit="8" filter="primary_tag:'development'"}}
  {{#foreach posts visibility="all"}}
    // ... (posts)

But if you do this your pagination won't work correctly. You'll see a mismatch between the number of posts paginated and the number of posts displayed, as the pagination block continues to iterate over entire posts collection and not your filtered/reduced set.

After some poking around I discovered that Ghost has a feature that allows you to filter content for an entire route. You can find it under Settings > Labs in your admin panel.

Dynamic Routing allows you to customise the default URL structure to fit your needs. Handily, for us, it also enables you to set up a channel - a custom stream of paginated content that matches a filter.

By default, routes.yaml looks like this:

routes:

collections:
  /:
    permalink: /{slug}/
    template: index

taxonomies:
  tag: /tag/{slug}/
  author: /author/{slug}/

Simply add the following to routes:

routes:
  /:
    controller: channel
    filter: 'tag:your-tag'

This sets up a channel for your homepage route :/ and filters the content by #your-tag.