I found a short snippet for string-interpolation on GitHub and shortened it to this:
var interpolate = function (tmpl, data) {
return new Function('data', 'with(data){return \'' +
tmpl.replace(/{{\s*(.+?)\s*}}/g, '\'+($1)+\'') + '\';}')(data);
};
It works fine for this:
interpolate('Hello {{user.name}}!', {user: {name: 'Admin'}});
// Hello Admin!
But there are two results I don´t like:
interpolate('Hello {{user.firstname}}!', {user: {name: 'Admin'}});
// Hello undefined!
and this one:
interpolate('Hello {{user.name}}!', {userinfo: {name: 'Admin'}});
// Uncaught ReferenceError: user is not defined(…)
Is there a way to modify the snipped to use a default (empty string) if the key does not exist?
UPDATE Now I found a solution for all my requirements:
function interpolate(tmpl, data, defaultValue, reg) {
return tmpl.replace(reg || /{{([^{}]*)}}/g, function(a, b) {
try {
return new Function('data', ['with(data){return ',b,' || \'',(defaultValue || ''),'\';}'].join(''))(data);
}
catch(e) {
return defaultValue || '';
}
});
}
interpolate('Existing value: {{user.name}} - global value: {{Date.now()}} - undefined: {{user.age}} - exception: {{dat.haha}}', {user: {name: 'Admin'}}, '?');
// "Existing value: Admin - global value: 1441555682168 - undefined: ? - exception: ?"
Suggestions are wellcome!