Details:
Assemble: 0.4.4
Grunt: 0.4.1
Question:
I'm designing a blog where I want to put 5 of the most recent posts on the front page. I've created a collection for my posts based on keywords:
assemble: {
options: {
flatten: false,
partials: '<%= build.src %>/_partials/*.hbs',
layoutdir: '<%= build.src %>/_layouts',
data: ['<%= build.src %>/_data/*.{json,yml}', 'package.json'],
assets: '<%= build.out %>/',
helpers: [ 'helper-moment','<%= build.src %>/helpers/helper-*.js'],
collections: [
{ name: 'keywords', inflection: 'keyword' }
]
},
YAML front matter on the various posts look similar to this:
--
layout: default.hbs
title: <%= site.title %>
description: "Adult Redeploy All Sites Summit 2015"
dateCreated: 06-23-2014
slug: "Welcome"
breadCrumbs: false
posted: 01-12-2014
keywords:
- news
navSort: 100
--
My code to display the titles and summaries is this:
<div>
{{#each keywords}}
{{#is keyword "news"}}
{{#withSort pages "data.posted" dir="desc"}}
<div>
<h2><a href="/{{relativeLink}}">{{data.title}}</a></h2>
<p>{{formatDate data.posted "%F"}}</p>
<div>
{{#markdown}}{{data.summary}}{{/markdown}}
</div>
<p><a href="/{{relativeLink}}">more...</a></p>
</div>
{{/withSort}}
{{/is}}
{{/each}}
</div>
This works. It displays all the blogs no problem. But I want to limit to 5 -- the five most recent.
I've looked at this issue:
https://github.com/assemble/assemble/issues/463
But I'm not sure how to incorporate it into the example above. Is there a way to limit the pages #withSort?
Confused.
There's good news and bad news. The bad news is that I don't believe there is a built-in helper that both sorts and limits the pages collection, nor can you piece two of them together in a pipeline.
Edited: I was wrong, there may be a built-in way combining collection sorting and the withFirst helper. I'll make a separate answer.
The good news is that you can write your own custom Handlebars Helper to do this. I wrote a sample helper below based on the withSort Helper. You would use it like this:
withSortLimit.js Here is the no-frills source to the withSortLimit helper. You will need to register this in your Gruntfile's Assemble configuration as described in the options.helpers docs.