Skip to content

Instantly share code, notes, and snippets.

@cerebrl
Created March 11, 2015 23:07
Show Gist options
  • Save cerebrl/2ae8f4f14256d37dc5bd to your computer and use it in GitHub Desktop.
Save cerebrl/2ae8f4f14256d37dc5bd to your computer and use it in GitHub Desktop.
Simple Server-Side String Interpolation. Demo: http://jsbin.com/pipudujixo/1/edit. Requires safeGet() here: https://gist.github.com/cerebrl/a52b69aafa9bf820bb1e
/* Simple, Server-Side String Interpolation
* Base on John Resig's Microtemplating: http://ejohn.org/blog/javascript-micro-templating/
*
* @param str {String} A string with key or object path in handlebar-like syntax: e.g. {{user.name}}
* @param data {Object} The data source with with to grab the key matching values
* @return {String} The final string with key-value replacements
*/
var safeInterpolate = function safeInterpolate (str, data){
// Create a new function with the template converted into executable code.
var fn = new Function("obj",
// The array to which the strings will be pushed.
"var p=[];" +
// Introduce the data as local variables using with()
"with (obj) {" +
"p.push('" +
// Convert the template into an array of pure strings and values.
// If item is a key, do a safeGet() to grab the value
str.replace(/[\r\t\n]/g, " ") // Normalize whitespace
.split("{{").join("\t") // Split string on the opening template key notation
.replace(/\t(.*?)}}/g, "',safeGet(obj, '$1'),'") + // Grabs the object key or dot notated path
"');" + // Close push syntax
"}" +
// Converts the array to a final string.
"return p.join('');");
return data ? fn(data) : str;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment