I'm creating a slide - so there's 3 images every one div like so
<div>
<img />
<img />
<img />
</div>
</div>
<img />
<img />
<img />
</div>
None of the code around the internet works flawlessly -
https://github.com/johanpoirier/resthub-backbone-stack/commit/8a318477d56c370d2a0af4da6eae9999c7bb29da
http://jaketrent.com/post/every-nth-item-in-handlebars-loop/
http://rockycode.com/blog/handlebars-loop-index/
http://www.arlocarreon.com/blog/javascript/handlebars-js-everyother-helper/
and yes including the answers here in stack overflow.
Can anyone provide some code that works perfectly at this current period (version of Ember/Handlebar)?
I have an array of models so i'd like to do something like
{{#each model}}
{{if index % 3 == 0}}
{{/if}}
{{/each}}
Ember uses the Handlebars templating library to power your app's user interface. Handlebars templates contain static HTML and dynamic content inside Handlebars expressions, which are invoked with double curly braces: { {}}.
This helper will output a value of 6. Ember ships with several built-in helpers, which you will learn more about in the following guides. Helpers have the ability to be nested within other helper invocations and also component invocations.
In Ember this is often a component. For templates rendered by a route (like application.hbs ), the context is a controller. For example, this application.hbs template will render a first and last name: Hello, <strong>{ {firstName}} { {lastName}}</strong>!
Thus, many of Ember's built-in helpers (as well as your custom helpers) can be used in nested form.
I have been finding that index
or @index
do not work from within the template, but you can access it from within a helper.
I've made an example here that demonstrates this:
http://jsbin.com/egoyay/1/edit
Edit: Adding code to answer, demonstrating {{else}}
block
Handlebars helper (for non-Ember use):
Handlebars.registerHelper('ifIsNthItem', function(options) {
var index = options.data.index + 1,
nth = options.hash.nth;
if (index % nth === 0)
return options.fn(this);
else
return options.inverse(this);
});
Usage:
<ol>
{{#each model}}
<li>
{{#ifIsNthItem nth=3}}
Index is a multiple of 3
{{else}}
Index is NOT a multiple of 3
{{/ifIsNthItem}}
</li>
{{/each}}
</ol>
If you specify itemViewClass
in each
helper, then it will create a view for each item and set contentIndex property:
{{#each model itemViewClass="Ember.View"}}
{{view.contentIndex}}
{{/each}}
tested in Ember v1.1.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With