Skip to content

Instantly share code, notes, and snippets.

@victorpavlenko
Created March 26, 2015 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save victorpavlenko/8605641fa2f57b043e84 to your computer and use it in GitHub Desktop.
Save victorpavlenko/8605641fa2f57b043e84 to your computer and use it in GitHub Desktop.
var HandlebarsService = (function(){
const PATH_TO_TEMPLATE = '/js/templates/';
var HandlebarsService = function() {
};
$.extend(HandlebarsService.prototype, {
get: function(templateName, data) {
var compiled = '';
templateName = templateName || '';
data = data || {};
$.ajax({
url: this.getTemplateURL(templateName),
type: 'GET',
async: false,
dataType: 'json',
success: function(response) {
compiled = this.compile(response, data)
}.bind(this),
error: function(err) {
console.error(err)
}.bind(this)
});
return compiled;
},
getFromNode: function(selector, data) {
var $node = null;
selector = selector || '';
data = data || {};
if (typeof(selector) === 'string') {
$node = $(selector);
} else if (selector instanceof jQuery) {
$node = selector;
}
return this.compile($node.html(), data);
},
getJQueryFromNode: function(selector, data) {
return $(this.getFromNode(selector, data));
},
compile: function(template, data) {
return Handlebars.compile(template)(data);
},
getTemplateURL: function(template) {
var path = template || '';
if (path[0] === '/') {
path = path.substr(1);
}
if (path.length < 5) {
path += '.hbs';
} else if (path.substr(path.length - 4) !== '.hbs') {
path += '.hbs';
}
console.log(PATH_TO_TEMPLATE + path);
return PATH_TO_TEMPLATE + path;
}
});
return new HandlebarsService();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment