Created
April 21, 2014 23:00
-
-
Save ShivrajRath/11159443 to your computer and use it in GitHub Desktop.
Handlebar Utilities
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Utility function to populate handlebar template.