Foreach loop in Ghost CMS returning null

1k views Asked by At

Currently setting up a simple site using Ghost CMS. By default, the homepage comes with a list of posts that it retrieves through a foreach loop. I'm trying to recreate that on the posts page, but nothing is being pulled in.

File structure is:

/theme
/theme/index.hbs
/theme/post.hbs

The code that works on the index.hbs is:

{{#foreach posts}}
<article class="{{post_class}}">
    <header class="post-header">
        <h2 class="post-title"><a href="{{url}}">{{{title}}}</a></h2>
    </header>
    <section class="post-excerpt">
        <p>{{excerpt words="26"}} <a class="read-more" href="{{url}}">&raquo;</a></p>
    </section>
    <footer class="post-meta">
        {{#if author.image}}<img class="author-thumb" src="{{author.image}}" alt="Author image" nopin="nopin" />{{/if}}
        {{author}}
        {{tags prefix=" on "}}
        <time class="post-date" datetime="{{date format='YYYY-MM-DD'}}">{{date format="DD MMMM YYYY"}}</time>
    </footer>
</article>
{{/foreach}}

My slightly stripped down version that I use on the post.hbs page is:

<aside class="timeline">
    {{#foreach posts}}
        <h4 class="post-title"><a href="{{url}}">{{{title}}}</a></h4>
        <section class="post-meta">
            {{author}}
            {{tags prefix=" on "}}
            <time class="post-date" datetime="{{date format='YYYY-MM-DD'}}">{{date format="DD MMMM YYYY"}}</time>
        </section>
    {{/foreach}}
</aside>

My guess is that I can't call posts while on the post page, but I'm not sure.

1

There are 1 answers

0
howtoinstallghost On

You cannot loop through all the posts on a post page. The post page is specifically for a single post. You can create custom static pages though which sounds like what you want.

What you want to do, is create a blank post with a title and page url (lets say the page url is blog.com/stuff). Make this post a static page. Then in your theme files, create a new file called page-stuff.hbs (stuff being the url of the static page). Then here you can do the foreach loop for the posts and grab whatever you want.