1

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.

4

1 回答 1

1

您的模板和助手很好。您使用它们的方式:

Handlebars.compile( $('#status').html() )(obj).appendTo('body')

虽然没有意义。Handlebars.compile返回一个函数,调用该函数会产生一个字符串;这意味着您appendTo实际上看起来像这样:

var tmpl = Handlebars.compile($('#status').html());  // Okay
var html = tmpl(obj);                                // Okay
html.appendTo('body');                               // Broken.

字符串没有appendTo方法。您可以将 a 包裹$()在字符串周围:

$(
    Handlebars.compile($('#status').html())(obj)
).appendTo('body');

或者一步一步做,让代码更清晰:

var tmpl = Handlebars.compile($('#status').html());
$('body').append(tmpl(obj));

演示:http: //jsfiddle.net/ambiguous/46sfd/

于 2013-03-03T18:47:35.503 回答