Created
December 15, 2011 22:57
-
-
Save afahy/1483369 to your computer and use it in GitHub Desktop.
Simple templating / string replacement function
This file contains 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
( 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'} ) ); | |
*/ |
This file contains 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
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