Creating a "Recent Posts" Loop
1 min read

Creating a "Recent Posts" Loop

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”}}