Skip to content

Instantly share code, notes, and snippets.

@mocheng

mocheng/template.js

Created Feb 14, 2011
Embed
What would you like to do?
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