Nesting if within each


#1

Hi, I’m a beginner to Ember.js and I’m writing an application in which I have a Post model that has a field called extended. I want to loop through each of the Posts and check if its extended field contains a String (say “hi”). I tried this:

{{#each model}} {{#if extended.indexOf(“abc”) != -1}}

But I get this error: Uncaught Error: Parse error on line 10: … {{#if extended.indexOf(“hi”) != 0}} ----------------------^ Expecting ‘ID’, got ‘INVALID’

Any ideas on how to properly do this?


#2

You can’t check like this in handlebars if block, you can check against true or false.

You can use the if helper to conditionally render a block. If its argument returns false, undefined, null, “” or [] (a “falsy” value), Handlebars will not render the block.

So, you have to keep a computed property in your Post model, which returns true or false based on the condition, and check against that in the handlebars

Say, in your Post Model, have a property

     isHi: function() { 
         return this.get('extended').indexOf("abc") != -1}
     }.property('extended')

and in your handlebars,

{{#each model}}
{{#if isHi}}

#3

Handlebars are logic-less templates where these sort of checks cannot be done. I suggest you to look through http://handlebarsjs.com/ … Alternatively, you can also specify itemController for your model in the each helper and handle these sort of logic there

{{#each itemController="applicationItem"}} {{#if testString}} {{name}} {{/if}} {{/each}}

App.ApplicationItemController = Em.ObjectController.extend({
 testString: function(){
  return this.get('name').indexOf("e") !== -1;
 }.property('content') 

});

Sample working jsbin


#4

Thanks for the help guys!