EMBER WORKSHOP: Ember.js Template Handlebars helpers Dependent Keys
Ember.js Template Handlebars Dependent Keys
by jdcravens
HTML
<script src="http://builds.emberjs.com/handlebars-1.0.0.js"></script>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://builds.emberjs.com/release/ember.js"></script>
<h3>Ember.js Template - Handlebars</h3>
<script type="text/x-handlebars">
<p>{{outlet}}</p>
</script>
<script type="text/x-handlebars" data-template-name="profile">
<h2>Profiles:</h2>
{{#each}}
<h2>{{NameWithClan}}</h2>
{{#with status}}
{{#if isOnline}}
<p>{{color isOnline}}</p>
{{else}}
{{#if isActive}}
<p>{{color isOnline}}</p>
{{else}}
<p>{{color isActive}}</p>
{{/if}}
{{/if}}
{{/with}}
{{/each}}
</script>
CSS
.online{
color: green;
}
.offline{
color: red;
}
.inactive{
color: brown;
}
JavaScript
var App = Em.Application.create();
Ember.Handlebars.helper('color', function(value, options) {
console.log(value);
console.log(options);
console.log(options.contexts[0].isActive);
if(value){
return new Ember.Handlebars.SafeString('<span class="online">User is online</span>');
}else if(!value && options.contexts[0].isActive){
return new Ember.Handlebars.SafeString('<span class="offline">User is offline</span>');
}else if(!value && !options.contexts[0].isActive){
var escaped = Handlebars.Utils.escapeExpression(value);
return new Ember.Handlebars.SafeString('<span class="inactive">User is inactive</span>');
}
});
Ember.Handlebars.helper('NameWithClan', function(value) {
console.log(value.contexts[0]);
return value.contexts[0].name + ' of ' + value.contexts[0].clan;
}, 'name', 'clan'); // this will be easier to do later when we are fully using Ember
// THE FOLLOWING WILL MAKE MORE SENSE LATER
// IGNORE FOR NOW
App.Router.map(function () {
this.route('profile');
});
App.IndexRoute = Ember.Route.extend({
redirect: function() {
this.transitionTo('profile');
}
});
App.ProfileRoute = Ember.Route.extend({
model: function(){
return [
{
name: 'CrafterJohn',
clan: 'the Forgotten',
status: {isActive: true, isOnline: true}
},
{
name: 'MinerPaul',
clan: 'the Rebels',
status: {isActive: true, isOnline: false}
},
{
name: 'ExplorerRingo',
clan: 'the Legends',
status: {isActive: false, isOnline: false}
}
];
},
});