Skip to content

Instantly share code, notes, and snippets.

@kevinohara80
Created January 18, 2012 21:05
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 kevinohara80/1635655 to your computer and use it in GitHub Desktop.
Save kevinohara80/1635655 to your computer and use it in GitHub Desktop.
Mustache merge class for Salesforce
public class MergeTool {
public static String mustacheMerge(String text, SObject obj) {
String p = '\\{\\{([^\\{\\}]*?)\\}\\}';
Pattern patt = Pattern.compile(p);
Matcher mat = patt.matcher(text);
Boolean foundValue = mat.find();
if(foundValue) {
do {
System.debug('GROUP 1: ' + mat.group(1));
String value;
try {
value = (String) obj.get(mat.group(1));
System.debug('Value: ' + value);
} catch (Exception e) {
System.debug('Error on ' + mat.group(1));
System.debug(e);
}
if(value != null) {
text = text.replaceFirst('\\{\\{' + mat.group(1) + '\\}\\}', value);
}
foundvalue = mat.find();
} while (foundvalue);
}
return text;
}
}
Lead ld = new Lead(FirstName = 'Kevin', LeadSource = 'Internet');
String test = 'This is {{FirstName}} from the {{LeadSource}}!';
String s = MergeTool.mustacheMerge(test, ld);
System.debug('String: ' + s);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment