As documented here: http://www.jblotus.com/2011/05/24/keeping-your-handlebars-js-templates-organized/
I am trying to use this function:
(
function getTemplateAjax(path, callback) {
var source;
var template;
$.ajax({
url: path,
success: function(data) {
source = data;
template = Handlebars.compile(source);
//execute the callback if passed
if (callback) callback(template);
}
});
}
//run our template loader with callback
(getTemplateAjax('js/templates/handlebarsdemo.handlebars', function(source) {
//do something with compiled template
$('body').html(template);
})()
)()
I am new to JS, so how can I use this?
I am trying to:
- pass the path of the handlebars file
- pass a json object which will be inserted in the template and an html should be returned back by the functions.
Update:
Got the answer, there was a typo in the code: this works.
While calling the function, the argument was source but was being used as template.
function getTemplateAjax(path, callback) {
var source;
var template;
$.ajax({
url: path,
success: function(data) {
source = data;
template = Handlebars.compile(source);
if (callback) callback(template);
}
});
}
getTemplateAjax('js/templates/handlebarsdemo.handlebars', function(template) {
data = {title: "hello!" , body: "world!"}
$('body').html(template(data));
})
The code is correct and you seem to be calling it correctly.
You should make sure that you have jQuery properly setup (just check the value of the jQuery global variable – it should not be “undefined”).
Also, you should check if the handlebars really is where you think it is – maybe you should be using an absolute URL instead of a relative one.