Shared Physics
by Roman Kudryashov
Shared Physics

Creating a "Recent Posts" Loop

Published on 1 min read

TLDR: A walkthrough for how to create a "Recent Posts" loop in Ghost.

The handlebars code that Ghost runs on isn't too complicated once you start digging into it. All of the logic for the recent posts loop is handled in the {{get}} logic, documented here. Here's the skeleton of the code I used to build the recent posts loop:

{{#get "posts" limit="5" include="tags" order="published_at desc"}}
  {{#foreach posts}}
    <p><a href="{{url}}">{{title}}</a> | {{date}}, {{tags separator=", "}}</p>
  {{/foreach}}
{{/get}}

url,  title, and date are automatically pulled in but you need to manually include author and tags if you want to show those. published_at and date both show you the published date, but the former is a full timestamp use for sort order while the latter is the reader-friendly version.

Wrap that up in some CSS to make it look pretty and then add it to the index.hbs file. Here's my final version:

<!-- Recent Posts -->
  <div style="background-color: #f7f7f7;padding: 40px 50px 20px 50px;margin-bottom: 50px;">
    <h3 style="padding-bottom: 20px; border-bottom: 1px solid #ccc;margin-bottom: 20px;">Recent Posts</h3>
  {{#get "posts" limit="5" include="tags" order="published_at desc"}}
      {{#foreach posts}}
      <p><a href="{{url}}">{{title}}</a> <span style="font-size: 0.8em !important; opacity:0.5;">{{date}} | <span style="padding: 3px 7px; border-radius: 3px; border: 1px solid #e0e0e0;">{{tags separator=", "}}</span></span></p>
      {{/foreach}}
  {{/get}}
  </div>
<!-- End Recent Posts -->

Creating a Pages loop was similar. Just replace posts with pages in the appropriate area.

Lastly, it took a bit of sleuthing to figure out how to exclude content. This was done via adding a - before the thing you're filtering. For example:

{{#get “tags” filter=“slug:-about”}}

Thanks for reading

Useful? Interesting? Have something to add? Shoot me a note at roman@sharedphysics.com. I love getting email and chatting with readers.

You can also sign up for irregular emails and RSS updates when I post something new.


Who am I?

I'm Roman Kudryashov. I'm a healthcare technologist and organizational fixer with too many side projects. I typically work with early and mid-stage companies to build, fix, or scale operations. I've done this for product, engineering, data, marketing, and design teams. My longer background is here and I keep track of some of my side projects here.


Stay true,
Roman