Skip to content

Instantly share code, notes, and snippets.

@lucasmotta
Last active August 10, 2018 07:52
Show Gist options
  • Save lucasmotta/9a2e7e3128d0dd282e5a to your computer and use it in GitHub Desktop.
Save lucasmotta/9a2e7e3128d0dd282e5a 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