Created
March 15, 2010 11:41
-
-
Save jimeh/332765 to your computer and use it in GitHub Desktop.
mustache.js — Super-simple Mustache-style text-replacement.
This file contains hidden or 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
/* | |
Super-simple Mustache-style text-replacement. | |
Example: | |
var data = {name: "James", location: "Mars"}; | |
mustache("Welcome to {{location}}, {{ name }}.", data); // => Welcome to Mars, James. | |
*/ | |
function mustache(string, data){ | |
if (typeof(string) === "string" && typeof(data) === "object") { | |
for (var key in data) { | |
string = string.replace(new RegExp("{{\\s*" + key + "\\s*}}", "g"), data[key]); | |
} | |
}; | |
return string; | |
}; |
@xyzshantaram Regex are not very user friendly, I suggest using this instead:
export const mustache = (string: string, data: Object) => Object.entries(data).reduce((res, [key, value]) => {
const search = `{${key}}`
if (
res.indexOf(search) !== -1 &&
res.indexOf(`\\${key}`) == -1 && // Escaped on start
res.indexOf(`${key}\\`) == -1 // Escaped on end
) {
return res.replace(search, value)
}
return res
}, string)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Borrowed from @etgrieco's version to make this, it supports escaping via backslashes.
(This is TypeScript ofc, you'd remove the annotations from the function signature to make it regular JS)