My goal is to put all my Handlebars templates in a single folder, as so:
templates/products.hbs
templates/comments.hbs
I found this snippet in a few places via a cursory Google search, which apparently will load in Handlebar templates in external files, which makes much more sense than putting a bunch of templates in a single index file.
(function getTemplateAjax(path) {
var source;
var template;
$.ajax({
url: path, //ex. js/templates/mytemplate.handlebars
cache: true,
success: function(data) {
source = data;
template = Handlebars.compile(source);
$('#target').html(template);
}
});
})()
The problem is, I don't understand this function or how to use it. Why is the whole function wrapped in parentheses and then made a function call? e.g. (function x() { ... })()
I don't know what this is doing.
And if I'm not mistaken, looks like $('#target')
is hardcoded when it shouldn't be. Furthermore, isn't this supposed to set a data
variable somewhere so the variables referenced in the template will work?? Seems the correct function should be:
function getTemplateAjax(path, target, jsonData) {
var source;
var template;
$.ajax({
url: path, //ex. js/templates/mytemplate.handlebars
cache: true,
success: function(data) {
source = data;
template = Handlebars.compile(source);
$(target).html(template(jsonData));
}
});
}
Side note: if someone could point me to a better template engine, one that actually natively supports external template files, and is better organized than Handlebars, I'd be eternally grateful.
Another issue: I can't actually name my files mytemplate.hbs
, because when the Ajax call happens, it sees it as a binary file and it comes through as binary. I suppose this is an issue of setting the server's mime type for .hbs to text/html or text/plain, but the issue is that this is a Grunt server and I'm not sure how to change its mime types.
text
plugin for require.js to dynamically load template files for handlebars: github.com/requirejs/text – Nicholas Cloud