Skip to content

Instantly share code, notes, and snippets.

@afahy
Created December 15, 2011 22:57
Show Gist options
  • Save afahy/1483369 to your computer and use it in GitHub Desktop.
Save afahy/1483369 to your computer and use it in GitHub Desktop.
Simple templating / string replacement function
( function( $ ) {
function Template( src ) {
if ( src && typeof src === 'string' ) {
this.src = src;
}
}
$.extend( Template.prototype, {
render : function( data ) {
return this.src.replace(/\$\{\s?([a-zA-Z_$][0-9a-zA-Z_$]*?)\s?\}/g, function(match, key) {
return data && data[key] ? data[key] : '';
} );
}
} );
$.fn.template = function() {
return new Template ( this.eq( 0 ).html() );
};
}( jQuery ) );
/*
console.log( $('#test').template().render( { msg: 'Hello World'} ) );
*/
function tmpl(str, data) {
return str.replace(/\$\{\s?([a-zA-Z_$][0-9a-zA-Z_$]*?)\s?\}/g, function(match, key) {
return data && data[key] ? data[key] : '';
} );
}
/*
var str = tmpl("Hello ${ $_ }; this is a message: ${ msg }", { $_: 'Dollar Underscore', msg: "\"I work!!\"" } );
console.log(str);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment