Skip to content

Instantly share code, notes, and snippets.

@mocheng
Created February 14, 2011 02:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mocheng/825411 to your computer and use it in GitHub Desktop.
Save mocheng/825411 to your computer and use it in GitHub Desktop.
Simple template function to replace pattern in string with object properties or function returned value.
/**
* Simple template function.
*
* For each pattern in argument template, it is replaced with actual property from argument data.
* t('{greeting} world', {greeting: 'hello'}) === 'hello world'
*
* Sequence of property in argument data doesn't matter:
* t('{g} {x}', {g: '{o}', o: 'x'})) === '{o} {x}'
* t('{g} {x}', {o: 'x', g: '{o}'})) === '{o} {x}'
*
* If matching pattern is function in property of argument data, the function is invoked with two arguments:
* The matching pattern and the whole input string.
* t('{greeting} world', {greeting: function(key, str) { return 'hello ' + key; } }) === 'hello greeting world'
*
* @argument str template string
* @argument data the actual data
*/
function t(str, data){
return str.replace(/\{([^\}]+?)\}/g, function(match, key) {
return (key in data)
? (typeof data[key] === 'function'? data[key](key, str) : data[key] )
: match;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment