Search code examples
twitter-bootstrapbootstrap-4handlebars.jsghost-blog

How to iterate through posts and make groups in Ghost


Hello fellow ghost writers,

I am basically developping my own theme based on Bootstrap. Therefore I want to create a carousel of links to article. I display 3 Bootstraps cards and I would like to add a caroussel. It is fairly easy as I just need to make a caroussel of card decks and put 3 cards per card deck.

But, there is a problem... How I tell Ghost to iterate through all posts and create "groups" of three posts ? Put differently: "foreach posts and every 3 posts do..."

I actually have:

        {{#foreach posts limit="3"}}
            {{> "post-card"}}
        {{/foreach}}

And I need something like:

        {{#foreach posts}}
            {{every 3 items}}
                <div class="card-deck">
                    {{> "post-card"}}
                </div>
        {{/foreach}}

I have really no idea how to start with that.

Regards


Solution

  • This can be done using @rowStart and @rowEnd when setting a columns value on the #foreach loop. Here's an example:

    {{#foreach posts columns="3"}}
        {{#if @rowStart}}<div class="card-deck">{{/if}}
            {{> "post-card"}}
        {{#if @rowEnd}}</div>{{/if}}
    {{/foreach}}
    

    By setting a columns to 3 @rowStart will signal the beginning of a column and @rowEnd will signal the end of a column.

    More info can be found in the Ghost handlebars docs: https://ghost.org/docs/api/v3/handlebars-themes/helpers/foreach/#data-variables

    Hope this helps!