Kuang-Cheng, Chien
8/10/2018 - 7:52 AM

A simple function to parse strings with {{mustache}} tags and replace its dot notation string to a given object path.

A simple function to parse strings with {{mustache}} tags and replace its dot notation string to a given object path.

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