Skip to content

Instantly share code, notes, and snippets.

@mattkahl
Last active March 16, 2017 08:23
Show Gist options
  • Save mattkahl/5077068 to your computer and use it in GitHub Desktop.
Save mattkahl/5077068 to your computer and use it in GitHub Desktop.
An asynchronous implementation of twigjs that returns a Promise on instantiation if the template is asynchronous. Works just like twig(), but when instantiated, twigAsync returns a Promise. The twig template is passed as the only parameter when resolving the Deferred object.
/**
* twig.async.js
*
* An asynchronous implementation of twigjs that returns a Promise on instantiation if the template is asynchronous.
* Works just like twig(), but when instantiated, twigAsync returns a Promise. The twig template
* is passed as the only parameter when resolving the Deferred object.
*
* e.g.
* tpl = twigAsync({href:'/templates/profile/profile-welcomeNewDesign.twig'});
* $.when(tpl).done(function(twigTemplate){
* var renderedHtml = twigTemplate.render({firstName:'Matt'});
* });
*
* Dependencies: Twig.js, jQuery
*/
window.twigAsync = function(options){
var defaults = {
// When true, return a Promise regardless if the template is loaded synchronously. When false,
// will return a Promise when asynchronous, a twigjs object otherwise.
isPromiseAlwaysReturned : true
},
// Initialize a Deferred to be eventually returned
deferred = $.Deferred(),
// Store the specified `load` option or a noop function if none is specified
_load = (typeof options.load !== 'undefined') ? options.load : $.noop,
// If the data option is defined, it overrides any href option
isRemote = typeof options.data === 'undefined',
// Is async undefined (because true is async's default) or set to true
isAsync = typeof options.async === 'undefined' || options.async === true,
template;
// Merge defaults with options
options = $.extend({},defaults,options);
_.defaults(options,defaults);
// If the template is being loaded asynchronously or remotely
if(isAsync && isRemote){
// Precede the `load` option with a function to resolve the deferred object
options.load = function loadTemplate(twigTemplate){
// Resolve the deferred object
deferred.resolve(twigTemplate);
// Run, if specified, the user's `load` option
_load(twigTemplate);
};
// Initialize the twig template, the deferred object will be resolved on load
template = twig(options);
// If the template is being loaded synchronously
} else {
// Initialize the twig template
template = twig(options);
// Return a Promise if specified
console.log(options);
if(options.isPromiseAlwaysReturned){
// Resolve the Deferred
deferred.resolve(template);
// Return a Promise
return deferred.promise();
} else {
//Return the twig template
return template;
}
}
// Return a the new Deferred object's Promise
return deferred.promise();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment