Created
December 20, 2013 05:13
-
-
Save ZellSnippets/8050638 to your computer and use it in GitHub Desktop.
JS: Render Handlebars template with ajax
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
/** | |
* Requests for Handlebars Templates with jquery ajax function | |
* | |
* Usage: | |
* var template = Handlebars.renderTemplate('templateName', templateData); | |
* | |
* Feel free to append template anywhere else after. | |
* | |
* @author : Zell Liew | |
* | |
* Code adapted from Tal Bereznitskey's Handlebars.getTemplate gist at https://gist.github.com/berzniz/2900905 | |
*/ | |
Handlebars.renderTemplate = function(name, data) { | |
var template; | |
if (Handlebars.templates === undefined || Handlebars.templates[name] === undefined) { | |
template = Handlebars.getTemplate(name); | |
} else { | |
template = Handlebars.templates[name]; | |
} | |
return template(data); | |
} | |
Handlebars.getTemplate = function(name) { | |
$.ajax({ | |
url: 'templates/' + name + '.html', | |
success: function(data) { | |
if (Handlebars.templates === undefined) { | |
Handlebars.templates = {}; | |
} | |
Handlebars.templates[name] = Handlebars.compile(data); | |
}, | |
async: false | |
}); | |
return Handlebars.templates[name]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment