Getting all the posts on the same date as the current item. With handlebars.

Stretching the limits of what handlebars can do, for fun and websites.

Getting all the posts on the same date as the current item. With handlebars.

It's been one of those weeks when I'm contemplating writing recursive handlebars, and really really wishing for a loop counter I can increment. But I'll spare you that, because it's ugly. Instead, behold! How to retrieve all posts published on the same date as a page.

OK, technically, I did write recursive handlebars a couple times. For those of you wondering, yes, it does pretty much crash Ghost, if you don't have some way to actually end the recursion. No, ctrl-C doesn't count.

Why would you want all posts on one date? Maybe you're making a collection of posts in an issue, without wanting to actually tag them? Or anyway, that's what I was doing...

{{!-- custom-issue-by-date.hbs --}}

<ul>
{{#page}}

<li> This page's date: {{date published_at format="YYYY-MM-DD HH:MM:SS"}}

{{> get-same-date-posts endDate=(date published_at format="YYYY-MM-DDT23:59:59Z") startDate=(date published_at format="YYYY-MM-DDT00:00:00Z")}}

{{/page}}
</ul>
{{!-- partials/get-same-date-posts --}}

{{#get "posts" limit="all" filter="published_at:<{{endDate}}+published_at:>{{startDate}}" }}
    {{#foreach posts}}
  <li>{{title}} {{date published_at format="YYYY-MM-DD HH:MM:SS"}}" </li>
    {{/foreach}}
{{/get}}

What in the world is going on there? Well, I'm cheating. It's a trick I've used before. I'm using Ghost's built in {{date}} helper in ways it probably wasn't meant to be used. The 'first handlebars file is getting the page's published_at date, taking advantage of the format argument to discard the actual time that the post was published at, instead creating valid datetime strings for the start and end of the day. Then (because filter is persnickety and doesn't like having the date function shoved into it), I pass those newly concocted dates (which are strings at this point) into a partial that actually makes the {{#get}} request for posts between startDate (00:00:00) and endDate (23:59:59), iterates through those posts with #foreach, and displays them.

πŸ‘‰Don't get confused by the parentheses when I'm passing startDate and endDate into get-same-date-posts – Ghost likes ( ) for functions inside 'stashes. Mostly.

πŸ’‘
Tip: Dates don't quite work right in SQLite3. It's a difference in how dates are encoded, and one of the reasons cross-database compatibility is a pain in the butt. If you're testing my code locally and it isn't working, that's probably why. This is one of those bugs that is a reason not to run SQLite3 in production. Seriously.

That concludes today's utterly weird blog post. Happy Monday!