Skip to content

Instantly share code, notes, and snippets.

@afahy
Created April 10, 2012 17:03
Show Gist options
  • Save afahy/2352882 to your computer and use it in GitHub Desktop.
Save afahy/2352882 to your computer and use it in GitHub Desktop.
Quick Underscore extension to get / precompile templates
/**
* _.getTemplate( selector ) returns a precompiled ( and cached ) template function based on selector html; assumes jQuery and Underscore
* @param { Selector } selector path to element ( most commonly a script tag with type= eg "x-underscore-template" ) containing template src
* @return {[type]} precompiled template function; pass in data object, returns rendered template text for .html() or .innerHTML =
*/
( function( global, _, undefined ) {
var templates = {};
_.getTemplate = function( selector ) {
var template = templates[ selector ] || ( function() {
var compiled = _.template( $( selector ).html() );
templates[ selector ] = compiled;
return compiled;
}() );
return template;
};
}( this, _ ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment