Skip to content

Instantly share code, notes, and snippets.

@kcchien
Forked from lucasmotta/parseMustache.coffee
Created August 10, 2018 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kcchien/027daa6e342068ff2d924b74eda0b75e to your computer and use it in GitHub Desktop.
Save kcchien/027daa6e342068ff2d924b74eda0b75e to your computer and use it in GitHub Desktop.
A simple function to parse strings with {{mustache}} tags and replace its dot notation string to a given object path.
parseMustache = (str, obj) ->
str.replace /{{\s*([\w\.]+)\s*}}/g, (tag, match) ->
nodes = match.split(".")
current = obj
for node in nodes
try
current = current[node]
catch
return ""
current
data = user:
name: "Lucas Motta"
bands: [
"Interpol"
"The National"
"Foo Fighters"
]
template = "Hello {{user.name}}. Your second favourite band is {{user.bands.1}}."
result = parseMustache(template, data)
alert(result)
function parseMustache(str, obj) {
return str.replace(/{{\s*([\w\.]+)\s*}}/g, function(tag, match) {
var nodes = match.split("."),
current = obj,
length = nodes.length,
i = 0;
while (i < length) {
try {
current = current[nodes[i]];
} catch (e) {
return "";
}
i++;
}
return current;
});
}
var data = {
user: {
name: "Lucas Motta",
bands: ["Interpol", "The National", "Foo Fighters"]
}
};
var template = "Hello {{user.name}}. Your second favourite band is {{user.bands.1}}.";
var result = parseMustache(template, data);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment