-
-
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.
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
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) |
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
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