Reputation: 57
I have created the following Handlebar template
<script type="text/template" id="status">
{{#completed status}}
<button class="btn btn-inverse">Close</button>
<button class="btn btn-primary">Submit</button>
<button class="btn btn-danger">Delete</button>
{{else}}
<button class="btn btn-primary">Close</button>
{{/completed}}
</script>
Here is my handlebar register helper
Handlebars.registerHelper('completed',function(item,options){
if (item == 'INITIATED'){
console.log(options.fn())
return options.fn();
}
else{
console.log(options.inverse());
return options.inverse();
}
});
And my javascript
obj={status: 'INITIATED'} and obj={status:'RECEIVED'}
Handlebars.compile( $('#status').html() )(obj).appendTo('body')
the status
variable in the template can have values INITIATED
or RECEIVED/COMPLETED
When I print in the console, I am getting the excepted buttons( once, the 3 buttons and the next time the one button) but in the html file I am getting the else section
only( both the times ).
I am not sure where I have gone wrong. Please advice.
Upvotes: 1
Views: 362
Reputation: 434585
Your template and helper are fine. The way you're using them:
Handlebars.compile( $('#status').html() )(obj).appendTo('body')
doesn't make sense though. Handlebars.compile
returns a function, calling that function produces a string; that means that your appendTo
actually looks like this:
var tmpl = Handlebars.compile($('#status').html()); // Okay
var html = tmpl(obj); // Okay
html.appendTo('body'); // Broken.
Strings don't have appendTo
methods. You could wrap a $()
around the string:
$(
Handlebars.compile($('#status').html())(obj)
).appendTo('body');
or do it step by step to make the code clearer:
var tmpl = Handlebars.compile($('#status').html());
$('body').append(tmpl(obj));
Demo: http://jsfiddle.net/ambiguous/46sfd/
Upvotes: 1