ember.js - Emberjs conditional output in a template with handlebars -
i got following models:
community name, members , moderators(both users). users, have id , name.
in communitymembers template want show users, , if user moderator, want add saying he's moderator
<script type="text/x-handlebars" data-template-name="communitymembers"> //model contains array of users in community {{#each user in model}} <li>{{user.name}}</li> {{#each moderator in controllers.community.moderators}} //here problem--> {{#if moderator.id == user.id}} <b>this moderator</b> {{/if}} {{/each}} {{/each}} </script>
i know in handlebars can't use moderator.id==user.id it's easy way want do.
i tried write handlebars helper when checked in helper argument got string saying: "moderator.id" or "user.id" didn't work.
i tried method in community-object:
app.community = ember.object.extend({ ismoderator: function(community, user_id){ return community.moderators.indexof({"id":user_id})!=-1; } });
in template:
{{#if ismoderator(controllers.community,user.id)}} <h>this moderator</h> {{/if}}
but gave me errors in template like:
. compiler said: error: parse error on line 12: .../if}}
{{#if ismoderator(controll
----------------------^ expecting 'close', 'close_unescaped', 'string', 'integer', 'boolean', 'id', 'data', 'sep', got 'invalid'
is there knows how deal this?
you can't in handlebars (as said) , shouldn't try mimic behavior helper. this limitation intentionally designed templating, because considered bad practice have logic in template. instead goal should write template this:
<script type="text/x-handlebars" data-template-name="communitymembers"> //model contains array of users in community {{#each user in controller.userswithmoderatorflag}} <li>{{user.name}}</li> {{#if user.ismoderator}} <b>this moderator</b> {{/if}} {{/each}} </script>
now asking how implement attribute. try (if can't embed attribute user objects):
app.communitymemberscontroller = ember.arraycontroller.extend({ needs : ["community"], userswithmoderatorflag : function(){ var moderators = this.get("controllers.community.moderators"); return this.get("model").map(function(user){ if(moderators.contains(user)){ user.set("ismoderator", true); } } }.property("model.@each", "controllers.community.moderators.@each") });
as can see, it quite easy move logic out of template , controller, belongs.
Comments
Post a Comment