Skip to content

Instantly share code, notes, and snippets.

@ShivrajRath
Created April 21, 2014 23:00
Show Gist options
  • Save ShivrajRath/11159443 to your computer and use it in GitHub Desktop.
Save ShivrajRath/11159443 to your computer and use it in GitHub Desktop.
Handlebar Utilities
/**
* Returns a template object from an external template file
* @param {[string]} templateURL [URL from the workspace from where the template file has to be read]
* @return {[string]} [Returns the template file content]
*/
function readTemplate(templateURL) {
if ( !! templateURL) {
var templateFile;
var templateAjax;
templateAjax = {
url: templateURL,
async: false,
cache: false,
success: function (template) {
templateFile = template;
}
};
$.ajax(templateAjax);
return (templateFile);
}
return {};
}
/**
* Populates handlebar template
* @param {[string]} id [ID of handlebar template script]
* @param {[jquery dom object/ String]} attacher [DOM elemember to which the populated template should be bound].
* E.g. ".class_name" or $(".class_name")
* @param {[Object]} data [The JSON data, which should be bound to the template]
* @return {[Populated Template]} [jQuery object with template populated]
*/
populateTemplate = function (id, attacher, data) {
try {
data = data || {};
if ( !! id && !! data && !! attacher) {
var scripts;
var src = this.getHTML(id);
var template = Handlebars.compile(src);
var html = template(data);
if (typeof attacher === "string") {
scripts = $(attacher).find('script').detach();
$(attacher).empty().append(scripts).append(html);
return $(attacher);
} else {
scripts = attacher.find('script').detach();
attacher.empty().append(scripts).append(html);
return attacher;
}
}
} catch (ex) {
console.log("Error in template binding: " + ex.message);
}
};
/**
* Get's html for an id
*/
getHTML = function (id) {
if ( !! id) {
return $("#" + id).html();
}
};
@ShivrajRath
Copy link
Author

Utility function to populate handlebar template.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment