Created
March 11, 2015 23:07
-
-
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
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, 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