Created
February 14, 2011 02:40
-
-
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.
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
/** | |
* 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