When you have a blog, sometimes you may want to feature your most popular or important posts above the others. You could do this in various ways but the easiest and recommended way is to use the get helper with some filtering to get the featured posts.
The typical place you would use to show featured post is your blog's homepage, so we will be modifying the index.hbs file of your Ghost theme. To get the featured posts in a query, we will use the featured filter:
{{#get "posts" limit="all" filter="featured:true"}}
{{#foreach posts}}
<a href="{{slug}}">{{title}}</a>
{{/foreach}}
{{/get}}
This code block will show all featured posts links with their title. You can add more post information in the foreach block, for example post excerpt and creation date:
{{#get "posts" limit="all" filter="featured:true"}}
{{#foreach posts}}
<a href="{{slug}}">{{title}}</a>
<p>{{excerpt}}</p>
<time datetime="{{date format=" YYYY-MM-DD"}}">{{date}}</time>
{{/foreach}}
{{/get}}
This would be enough to show the featured posts title, excerpt and date. However, we can improve this code in a few ways. First, we can check to see if there are featured posts at all. If there are no featured posts created on our blog, we can show a simple message to the user:
{{#get "posts" filter="featured:true" limit="all"}}
{{#if posts}}
{{#foreach posts}}
<a href="{{url}}">{{title}}</a>
<p>{{excerpt}}
<time datetime="{{date format=" YYYY-MM-DD"}}">{{date}}</time>
{{/foreach}}
{{else}}
<p>There are no featured posts at the moment.</p>
{{/if}}
{{/get}}
Also, we don't want to show featured posts if the post pagination is active. So, for example if the user switches to a different page using the pagination the featured posts section will not be shown. We can achieve this by combining our code with the is helper:
{{^is "paged"}}
{{#get "posts" filter="featured:true" limit="all"}}
{{#if posts}}
{{#foreach posts}}
<a href="{{url}}">{{title}}</a>
<p>{{excerpt}}
<time datetime="{{date format=" YYYY-MM-DD"}}">{{date}}</time>
{{/foreach}}
{{else}}
<p>There are no featured posts at the moment.</p>
{{/if}}
{{/get}}
{{/is}}
Here, we are using the negation form of the is helper by using the ^ character. So, essentially if the page is not paged, then the featured posts will be shown to the user.
Top comments (0)