{"category":{"version":"58810495d172b61b00d73859","project":"542fe92a5eceb608003fddc8","_id":"58810495d172b61b00d7385d","__v":0,"sync":{"url":"","isSync":false},"reference":false,"createdAt":"2014-10-04T12:45:40.548Z","from_sync":false,"order":3,"slug":"helper-reference","title":"Helper Reference"},"parentDoc":null,"project":"542fe92a5eceb608003fddc8","user":"542c5cfcddd3190e00228849","version":{"__v":1,"_id":"58810495d172b61b00d73859","project":"542fe92a5eceb608003fddc8","createdAt":"2017-01-19T18:25:25.206Z","releaseDate":"2017-01-19T18:25:25.206Z","categories":["58810495d172b61b00d7385a","58810495d172b61b00d7385b","58810495d172b61b00d7385c","58810495d172b61b00d7385d","58810495d172b61b00d7385e","58810495d172b61b00d7385f"],"is_deprecated":false,"is_hidden":false,"is_beta":false,"is_stable":true,"codename":"","version_clean":"0.11.4","version":"0.11.4"},"_id":"58810495d172b61b00d7387b","__v":0,"updates":[],"next":{"pages":[],"description":""},"createdAt":"2014-10-04T19:34:23.598Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"settings":"","auth":"never","params":[],"url":""},"isReference":false,"order":31,"body":"[block:html]\n{\n  \"html\": \"<div class=\\\"github-deeplinks\\\">\\n    <a href=\\\"https://github.com/TryGhost/Ghost/blob/0.10.0/core/server/helpers/foreach.js\\\"><i class=\\\"fa fa-github-alt fa-right\\\"></i>Source</a>\\n    <a href=\\\"https://github.com/TryGhost/Ghost/blob/0.10.0/core/test/unit/server_helpers/foreach_spec.js\\\" class=\\\"fa fa-check-square-o fa-right\\\">Tests</a>\\n</div>\"\n}\n[/block]\nUsage: `{{#foreach data}}{{/foreach}}`\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"Type\",\n    \"h-1\": \"Parameters\",\n    \"h-2\": \"Attributes\",\n    \"0-0\": \"[Block](/docs/helpers#section-block), [Ghost](/docs/helpers#section-ghost)\",\n    \"0-1\": \"* data (collection) - collection to loop over\",\n    \"0-2\": \"* `columns` (number)\\n* `limit` (number)\\n* `from` (number)\\n* `to` (number)\\n* `visibility` (string, default: \\\"public\\\")\",\n    \"h-3\": \"\"\n  },\n  \"cols\": 3,\n  \"rows\": 1\n}\n[/block]\n## Description\n\n`{{#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.\n\nThe `{{#foreach}}` helper is context-aware and should **always** be used instead of Handlebars `each` when working with Ghost themes.\n\n### Simple Example\n\nThe main use of the `{{#foreach}}` helper in Ghost is iterating over the posts to display a list of posts on your home page, etc:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{{#foreach posts}}\\n<article class=\\\"{{post_class}}\\\">\\n  <h2 class=\\\"post-title\\\"><a href=\\\"{{url}}\\\">{{{title}}}</a></h2>\\n  <p>{{excerpt words=\\\"26\\\"}} <a class=\\\"read-more\\\" href=\\\"{{url}}\\\">&raquo;</a></p>\\n  <p class=\\\"post-footer\\\">\\n    Posted by {{author}} {{tags prefix=\\\" on \\\"}} at <time class=\\\"post-date\\\" datetime=\\\"{{date format='YYYY-MM-DD'}}\\\">{{date format=\\\"DD MMMM YYYY\\\"}}</time>\\n  </p>\\n</article>\\n{{/foreach}}\",\n      \"language\": \"handlebars\"\n    }\n  ]\n}\n[/block]\n\n[block:callout]\n{\n  \"type\": \"success\",\n  \"title\": \"Note\",\n  \"body\": \"The `{{#foreach}}` helper can **only** operate on the data available to it in the current template scope. You can find out what data a template has access to by looking it up in the [context table](/docs/context-overview#context-table), and you can fetch additional data using the [get helper](/docs/get).\"\n}\n[/block]\n## Data Variables\n\nWhen inside a `{{#foreach}}` block, you have access to a set of data variables about the current iteration. These are:\n\n- **:::at:::index** (number) - the 0-based index of the current iteration \n- [email protected]** (number) - the 1-based index of the current iteration\n- [email protected]** (string) - if iterating over an object, rather than an array, this contains the object key\n- [email protected]** (boolean) - true if this is the first iteration of the collection\n- [email protected]** (boolean) - true if this is the last iteration of the collection\n- [email protected]** (boolean) - true if the @index is odd\n- [email protected]** (boolean) - true if the @index is even\n- [email protected]** (boolean) - true if `columns` is passed and this iteration signals a row start\n- [email protected]** (boolean) - true if `columns` is passed and this iteration signals a row end\n\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Usage\"\n}\n[/block]\n`{{#foreach}}` is a block helper. The most common use case in Ghost, is looping through posts.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{{#foreach posts}}\\n<h2><a href=\\\"{{url}}\\\">{{title}}</a></h2>\\n<p>{{excerpt}}</p>\\n{{/foreach}}\",\n      \"language\": \"handlebars\"\n    }\n  ]\n}\n[/block]\nIt's just as easy to loop through tags (although this is more easily done with the [tags helper](doc:tags)). \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<ul>\\n{{#foreach tags}}\\n<li><a href=\\\"{{url}}\\\">{{name}}</a></li>\\n{{/foreach}}\\n</ul>\",\n      \"language\": \"handlebars\"\n    }\n  ]\n}\n[/block]\n## {{else}} and negation\n\nLike all block helpers, `{{#foreach}}` supports adding an `{{else}}` block, which will be executed if there was no data to iterate over:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{{#foreach tags}}\\n<a href=\\\"{{url}}\\\">{{name}}</a>\\n{{else}}\\n<p>There were no tags...</p>\\n{{/foreach}}\",\n      \"language\": \"handlebars\"\n    }\n  ]\n}\n[/block]\nAgain, like all block helpers,  `{{#foreach}}` supports using `^` instead of `#` for negation - this means that the `{{#foreach}}` and `{{else}}` blocks are reversed if you use `{{^foreach}}` and `{{else}}` instead.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{{^foreach tags}}\\n<p>There were no tags...</p>\\n{{else}}\\n<a href=\\\"{{url}}\\\">{{name}}</a>\\n{{/foreach}}\",\n      \"language\": \"handlebars\"\n    }\n  ]\n}\n[/block]\n## The `limit` attribute\n\nPassing `{{#foreach}}` a `limit` attribute, will tell it stop after a certain number of iterations.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{{#foreach posts limit=\\\"3\\\"}}\\n{{! will stop after 3, no matter how many posts there are...}}\\n<a href=\\\"{{url}}\\\">{{name}}</a>\\n{{/foreach}}\",\n      \"language\": \"handlebars\"\n    }\n  ]\n}\n[/block]\nNote that as the `{{#foreach}}` helper is only passively iterating over data, not actively fetching it, if you set limit to a number higher than the number of items in the collection, it will have no effect.\n\n## The `from` and `to` attributes\n\nPassing  `{{#foreach}}` a `from` or `to` attribute will change the items which are output. Both attributes are 1-indexed and inclusive,  so `from=\"2\"` means from and including the 2nd post.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{{#foreach posts from=\\\"2\\\" to=\\\"5\\\"}}\\n{{! will start at the 2nd post, and stop at the 5th, outputting 3 posts, providing the posts per page setting is at least 5}}\\n<a href=\\\"{{url}}\\\">{{name}}</a>\\n{{/foreach}}\",\n      \"language\": \"handlebars\"\n    }\n  ]\n}\n[/block]\n## The `columns` attribute\n\nThe purpose of this is to help developers build grid layouts. For example, if you wanted to output your posts in a grid of 3 columns, you can use the `columns` attribute to pass this information to the `{{#foreach}}` helper, and it will then set handy [email protected]` and [email protected]` booleans you can use to add css classes:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{{#foreach posts columns=\\\"3\\\"}}\\n<section class=\\\"{{post_class}}{{#if @rowStart}} row-start{{/if}}{{#if @rowEnd}} row-end{{/if}}\\\">\\n<h2>{{title}}</h2>\\n<p>{{excerpt</p>\\n</section>\\n{{/foreach}}\",\n      \"language\": \"handlebars\"\n    }\n  ]\n}\n[/block]\nThis just makes it a little easier to style the left-most and right-most items in the grid.\n\n\n## The `visibility` attribute\n\nAs of Ghost 0.9 posts, tags and users all have a concept of `visibility`, which defaults to `public`. The key feature build on this so far is Internal Tags, which are tags where the `visibility` is marked as `internal` instead of `public`. These tags will therefore not be output in a `{{#foreach}}` loop unless you specifically ask for them.\n\nBy default the `visibility` attribute is set to the string \"public\". This can be overridden to pass any other value, and if there is no matching value for `visibility` nothing will be output. E.g. you can set `visibility` to be \"internal\" to _only_ output internal tags. You can also pass a comma-separated list of values, or the value \"all\" to output all items.\n\n```\n{{#foreach tags visibility=\"all\"}}\n```\n\n## Data variables\n\n### @index, @number and @key\n\[email protected]}}` is the index of the collection. It starts at 0 and then each time around the loop, [email protected]}}` increases by 1. This is useful for adding numbered classes:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{{#foreach posts}}\\n  <div class=\\\"[email protected]}}\\\">{{title}}</div>\\n{{/foreach}}\",\n      \"language\": \"handlebars\"\n    }\n  ]\n}\n[/block]\[email protected]}}` is very similar to [email protected]`, but starts at 1 instead of 0, which is useful for outputting numbers you want users to see, e.g. in styled numbered lists:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<ol>\\n{{#foreach posts}}\\n  <li>\\n    <a href=\\\"{{url}}\\\">\\n      <span class=\\\"number\\\" aria-hidden=\\\"true\\\">[email protected]}}</span>{{title}}\\n    </a>\\n  </li>\\n{{/foreach}}\\n</ol>\",\n      \"language\": \"handlebars\"\n    }\n  ]\n}\n[/block]\[email protected]}}` 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.\n\n### @first & @last\n\nThe following example checks through an array or object e.g `posts` and tests for the first entry.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{{#foreach posts}}\\n  {{#if @first}}\\n    <div>First post</div>\\n  {{/if}}\\n{{/foreach}}\",\n      \"language\": \"handlebars\"\n    }\n  ]\n}\n[/block]\nWe can also nest `if` statements to check multiple properties. In this example we are able to output the first and last post separately to other posts.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{{#foreach posts}}\\n    {{#if @first}}\\n    <div>First post</div>\\n    {{else}}\\n        {{#if @last}}\\n            <div>Last post</div>\\n        {{else}}\\n            <div>All other posts</div>\\n        {{/if}}\\n    {{/if}}\\n{{/foreach}}\",\n      \"language\": \"handlebars\"\n    }\n  ]\n}\n[/block]\n### @even & @odd\n\nThe following example adds a class of even or odd, which could be used for zebra striping content:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{{#foreach posts}}\\n        <div class=\\\"{{#if @even}}even{{else}}odd{{/if}}\\\">{{title}}</div>\\n{{/foreach}}\",\n      \"language\": \"handlebars\"\n    }\n  ]\n}\n[/block]\n## Block Params\n\nHandlebars recently added the concept of block params to its `{{#each}}` helper. In Ghost the `{{#foreach}}` helper has been upgraded to also support this feature. \n\nBlock params allow you to name the individual item being operated on inside the loop, E.g.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{{#foreach posts as |my_post|}}\\n   {{#my_post}}\\n      <h1>{{title}}</h1>\\n    {{/my_post}}\\n{{/foreach}}\",\n      \"language\": \"handlebars\"\n    }\n  ]\n}\n[/block]\nWhich is much the same as doing `posts.forEach(function (my_post) {}` in JavaScript. Useful with advanced features like the `{{get}}` helper.\n\n**Note:** Handlebars has a built-in each helper, but Ghost's `{{foreach}}` helper has extra functionality, so we always recommend using `{{foreach}}`.","excerpt":"`{{foreach}}` Helper - Loop through available template data (an extension to {{each}})","slug":"foreach","type":"basic","title":"foreach"}

foreach

`{{foreach}}` Helper - Loop through available template data (an extension to {{each}})

[block:html] { "html": "<div class=\"github-deeplinks\">\n <a href=\"https://github.com/TryGhost/Ghost/blob/0.10.0/core/server/helpers/foreach.js\"><i class=\"fa fa-github-alt fa-right\"></i>Source</a>\n <a href=\"https://github.com/TryGhost/Ghost/blob/0.10.0/core/test/unit/server_helpers/foreach_spec.js\" class=\"fa fa-check-square-o fa-right\">Tests</a>\n</div>" } [/block] Usage: `{{#foreach data}}{{/foreach}}` [block:parameters] { "data": { "h-0": "Type", "h-1": "Parameters", "h-2": "Attributes", "0-0": "[Block](/docs/helpers#section-block), [Ghost](/docs/helpers#section-ghost)", "0-1": "* data (collection) - collection to loop over", "0-2": "* `columns` (number)\n* `limit` (number)\n* `from` (number)\n* `to` (number)\n* `visibility` (string, default: \"public\")", "h-3": "" }, "cols": 3, "rows": 1 } [/block] ## Description `{{#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. ### Simple Example The main use of the `{{#foreach}}` helper in Ghost is iterating over the posts to display a list of posts on your home page, etc: [block:code] { "codes": [ { "code": "{{#foreach posts}}\n<article class=\"{{post_class}}\">\n <h2 class=\"post-title\"><a href=\"{{url}}\">{{{title}}}</a></h2>\n <p>{{excerpt words=\"26\"}} <a class=\"read-more\" href=\"{{url}}\">&raquo;</a></p>\n <p class=\"post-footer\">\n Posted by {{author}} {{tags prefix=\" on \"}} at <time class=\"post-date\" datetime=\"{{date format='YYYY-MM-DD'}}\">{{date format=\"DD MMMM YYYY\"}}</time>\n </p>\n</article>\n{{/foreach}}", "language": "handlebars" } ] } [/block] [block:callout] { "type": "success", "title": "Note", "body": "The `{{#foreach}}` helper can **only** operate on the data available to it in the current template scope. You can find out what data a template has access to by looking it up in the [context table](/docs/context-overview#context-table), and you can fetch additional data using the [get helper](/docs/get)." } [/block] ## Data Variables When inside a `{{#foreach}}` block, you have access to a set of data variables about the current iteration. These are: - [email protected]** (number) - the 0-based index of the current iteration - [email protected]** (number) - the 1-based index of the current iteration - [email protected]** (string) - if iterating over an object, rather than an array, this contains the object key - [email protected]** (boolean) - true if this is the first iteration of the collection - [email protected]** (boolean) - true if this is the last iteration of the collection - [email protected]** (boolean) - true if the @index is odd - [email protected]** (boolean) - true if the @index is even - [email protected]** (boolean) - true if `columns` is passed and this iteration signals a row start - [email protected]** (boolean) - true if `columns` is passed and this iteration signals a row end [block:api-header] { "type": "basic", "title": "Usage" } [/block] `{{#foreach}}` is a block helper. The most common use case in Ghost, is looping through posts. [block:code] { "codes": [ { "code": "{{#foreach posts}}\n<h2><a href=\"{{url}}\">{{title}}</a></h2>\n<p>{{excerpt}}</p>\n{{/foreach}}", "language": "handlebars" } ] } [/block] It's just as easy to loop through tags (although this is more easily done with the [tags helper](doc:tags)). [block:code] { "codes": [ { "code": "<ul>\n{{#foreach tags}}\n<li><a href=\"{{url}}\">{{name}}</a></li>\n{{/foreach}}\n</ul>", "language": "handlebars" } ] } [/block] ## {{else}} and negation Like all block helpers, `{{#foreach}}` supports adding an `{{else}}` block, which will be executed if there was no data to iterate over: [block:code] { "codes": [ { "code": "{{#foreach tags}}\n<a href=\"{{url}}\">{{name}}</a>\n{{else}}\n<p>There were no tags...</p>\n{{/foreach}}", "language": "handlebars" } ] } [/block] Again, like all block helpers, `{{#foreach}}` supports using `^` instead of `#` for negation - this means that the `{{#foreach}}` and `{{else}}` blocks are reversed if you use `{{^foreach}}` and `{{else}}` instead. [block:code] { "codes": [ { "code": "{{^foreach tags}}\n<p>There were no tags...</p>\n{{else}}\n<a href=\"{{url}}\">{{name}}</a>\n{{/foreach}}", "language": "handlebars" } ] } [/block] ## The `limit` attribute Passing `{{#foreach}}` a `limit` attribute, will tell it stop after a certain number of iterations. [block:code] { "codes": [ { "code": "{{#foreach posts limit=\"3\"}}\n{{! will stop after 3, no matter how many posts there are...}}\n<a href=\"{{url}}\">{{name}}</a>\n{{/foreach}}", "language": "handlebars" } ] } [/block] Note that as the `{{#foreach}}` helper is only passively iterating over data, not actively fetching it, if you set limit to a number higher than the number of items in the collection, it will have no effect. ## The `from` and `to` attributes Passing `{{#foreach}}` a `from` or `to` attribute will change the items which are output. Both attributes are 1-indexed and inclusive, so `from="2"` means from and including the 2nd post. [block:code] { "codes": [ { "code": "{{#foreach posts from=\"2\" to=\"5\"}}\n{{! will start at the 2nd post, and stop at the 5th, outputting 3 posts, providing the posts per page setting is at least 5}}\n<a href=\"{{url}}\">{{name}}</a>\n{{/foreach}}", "language": "handlebars" } ] } [/block] ## The `columns` attribute The purpose of this is to help developers build grid layouts. For example, if you wanted to output your posts in a grid of 3 columns, you can use the `columns` attribute to pass this information to the `{{#foreach}}` helper, and it will then set handy [email protected]` and [email protected]` booleans you can use to add css classes: [block:code] { "codes": [ { "code": "{{#foreach posts columns=\"3\"}}\n<section class=\"{{post_class}}{{#if @rowStart}} row-start{{/if}}{{#if @rowEnd}} row-end{{/if}}\">\n<h2>{{title}}</h2>\n<p>{{excerpt</p>\n</section>\n{{/foreach}}", "language": "handlebars" } ] } [/block] This just makes it a little easier to style the left-most and right-most items in the grid. ## The `visibility` attribute As of Ghost 0.9 posts, tags and users all have a concept of `visibility`, which defaults to `public`. The key feature build on this so far is Internal Tags, which are tags where the `visibility` is marked as `internal` instead of `public`. These tags will therefore not be output in a `{{#foreach}}` loop unless you specifically ask for them. By default the `visibility` attribute is set to the string "public". This can be overridden to pass any other value, and if there is no matching value for `visibility` nothing will be output. E.g. you can set `visibility` to be "internal" to _only_ output internal tags. You can also pass a comma-separated list of values, or the value "all" to output all items. ``` {{#foreach tags visibility="all"}} ``` ## Data variables ### @index, @number and @key [email protected]}}` is the index of the collection. It starts at 0 and then each time around the loop, [email protected]}}` increases by 1. This is useful for adding numbered classes: [block:code] { "codes": [ { "code": "{{#foreach posts}}\n <div class=\"[email protected]}}\">{{title}}</div>\n{{/foreach}}", "language": "handlebars" } ] } [/block] [email protected]}}` is very similar to [email protected]`, but starts at 1 instead of 0, which is useful for outputting numbers you want users to see, e.g. in styled numbered lists: [block:code] { "codes": [ { "code": "<ol>\n{{#foreach posts}}\n <li>\n <a href=\"{{url}}\">\n <span class=\"number\" aria-hidden=\"true\">[email protected]}}</span>{{title}}\n </a>\n </li>\n{{/foreach}}\n</ol>", "language": "handlebars" } ] } [/block] [email protected]}}` 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 The following example checks through an array or object e.g `posts` and tests for the first entry. [block:code] { "codes": [ { "code": "{{#foreach posts}}\n {{#if @first}}\n <div>First post</div>\n {{/if}}\n{{/foreach}}", "language": "handlebars" } ] } [/block] We can also nest `if` statements to check multiple properties. In this example we are able to output the first and last post separately to other posts. [block:code] { "codes": [ { "code": "{{#foreach posts}}\n {{#if @first}}\n <div>First post</div>\n {{else}}\n {{#if @last}}\n <div>Last post</div>\n {{else}}\n <div>All other posts</div>\n {{/if}}\n {{/if}}\n{{/foreach}}", "language": "handlebars" } ] } [/block] ### @even & @odd The following example adds a class of even or odd, which could be used for zebra striping content: [block:code] { "codes": [ { "code": "{{#foreach posts}}\n <div class=\"{{#if @even}}even{{else}}odd{{/if}}\">{{title}}</div>\n{{/foreach}}", "language": "handlebars" } ] } [/block] ## Block Params Handlebars recently added the concept of block params to its `{{#each}}` helper. In Ghost the `{{#foreach}}` helper has been upgraded to also support this feature. Block params allow you to name the individual item being operated on inside the loop, E.g. [block:code] { "codes": [ { "code": "{{#foreach posts as |my_post|}}\n {{#my_post}}\n <h1>{{title}}</h1>\n {{/my_post}}\n{{/foreach}}", "language": "handlebars" } ] } [/block] Which is much the same as doing `posts.forEach(function (my_post) {}` in JavaScript. Useful with advanced features like the `{{get}}` helper. **Note:** Handlebars has a built-in each helper, but Ghost's `{{foreach}}` helper has extra functionality, so we always recommend using `{{foreach}}`.