Usage: {{#foreach data}}{{/foreach}}
{{#foreach}}
is a special loop helper designed for working with lists of posts. It can also iterate over lists of tags or users if needed. The foreach helper will output the content placed between its opening and closing tags {{#foreach}}{{/foreach}}
once for each item in the collection passed to it.
The {{#foreach}}
helper is context-aware and should always be used instead of Handlebars each
when working with Ghost themes.
{{#foreach}}
helper in Ghost is iterating over the posts to display a list of posts on your home page, etc:
{{#foreach}}
block, you have access to a set of data variables about the current iteration. These are:
columns
is passed and this iteration signals a row startcolumns
is passed and this iteration signals a row’s end{{#foreach}}
is a block helper. The most common use case in Ghost is looping through posts.
{{#foreach}}
supports adding an {{else}}
block, which will be executed if there is no data to iterate over:
limit
attribute{{#foreach}}
a limit
attribute will tell it to stop after a certain number of iterations.
{{#foreach}}
helper is only passively iterating over data, not actively fetching it, if you set the limit to a number higher than the number of items in the collection, it will have no effect.
from
and to
attributes{{#foreach}}
a from
or to
attribute will change the items that are output. Both attributes are 1-indexed and inclusive, so from="2"
means from and including the 2nd post.
visibility
attributeforeach
only displays data that is public. This means that data like hidden tiers and internal tags won’t be included. Set visibility
to all
to show all data or to none
to show hidden data.
{{@number}}
is very similar to @index
, but starts at 1 instead of 0, which is useful for outputting numbers you want users to see, e.g. in styled numbered lists:
{{@key}}
will contain the object key, in the case where you iterate over an object, rather than an array. There’s no real use case for this in Ghost at present.
@first
& @last
posts
, and tests for the first entry.
if
statements to check multiple properties. In this example, we separate the output of the first and last posts from the other posts.
@even
& @odd
@rowStart
& @rowEnd
@rowStart
and @rowEnd
return true
at the beginning and end of a column respectively when the columns
value is set in a #foreach
. In the following example, the posts are being grouped up in threes with a wrapping div
element:
posts.forEach(function (my_post) {}
in JavaScript. Useful with advanced features like the {{get}}
helper.