In a template how to get posts count and check how many they are?

I would like to render something differently based on the number of posts on the page.
Is is possible? If yes how? Something like below, but does not work.

{{if posts.length="3"}}
{{if posts.length>"3"}}
{{if posts.length>="3"}}
{{if posts.length<"3"}}
{{if posts.length<="3"}}

I think you should check out the #foreach documentation:

There’s lots of handy helpers that get exposed inside a #foreach loop which you could use to style and modify posts depending on how many there are :blush:

Hi David,

I did check out the documentation countless times and I could not find a way to count the the number of posts and compare it to a number.

Please, can you be more specific with your answer?

It would be great if you could explain in more detail what you’re trying to achieve :blush:

I would like to render my theme homepage in a different way based on the number of posts.

I understand that part, but what is your final goal? Is it to change the presentation or the layout or something else? For example if you wanted to change the layout of the posts depending on the number of total posts you could apply a class to the container that includes the post count:

<div class="container post-count-{{#get "posts" limit="all"}}{{posts.length}}{{/get}}">

  {{#foreach posts}}
    {{> "post-card"}}
  {{/foreach}}

</div>

This is just an idea thought as I’m not sure what you’re trying to achieve :blush:

1 Like