I really want to implement your solution because it's scalable and the code is much cleaner than using if/then statements.
Just like Gerard, I was able to make the long if/then version work but I can't make yours work (with the dictionary/regex) - it always outputs the default value.
I run your test above and got the same result - default value.
What else could I check for?
Are you using Send Sample, or a real email? You must send a real email.
You did change the $testLeadN stuff to $lead, right?
Yes, I use ${lead.LastName}.
I was using test email but I just tried the real email and the result is the same.
Not sure why I would even have to send an email - I should be able to preview the result by selecting "View By" lead which works for the long if/then Velocity statement.
If you do Preview-by-List, yes, you don't have to send an email. But if you do send an email, it can't be a sample.
Please show the full code you're using in both cases (highlighted as Java using the Advanced Editor's syntax highlighter).
Code that always outputs the default value:
#set( $greetingsBySalutationStart = {
"Mr." : "Sehr geehrter Herr",
"Mrs." : "Sehr geehrte Frau",
"$" : "Sehr geehrte(r) Frau/Herr"
})
## ---- NO NEED TO TOUCH ANYTHING BELOW THIS LINE! ----
#set( $greeting = $greetingsBySalutationStart["$"] )
#foreach( $startPattern in $greetingsBySalutationStart.keySet() )
#if( $lead.Salutation.matches("^${startPattern}\b.*") )
#set( $greeting = "${greetingsBySalutationStart[$startPattern]} ${lead.Salutation}" )
#end
#end
${greeting} ${lead.LastName}
Code that works:
#if(${lead.Salutation} == "Mr.")
#set($greeting = "Sehr geehrter Herr ${lead.LastName},")
#elseif(${lead.Salutation} == "Mrs.")
#set($greeting = "Sehr geehrte Frau ${lead.LastName},")
#else
#set($greeting = "Sehr geehrte/r Frau/Herr ${lead.LastName},")
#end
${greeting}
Because when you include the . at the end, it no longer matches the word break \b.
Try this:
#set( $greetingsBySalutationStart = {
"Mr\.?" : "Sehr geehrter Herr",
"Mrs\.?" : "Sehr geehrte Frau",
"$" : "Sehr geehrte(r) Frau/Herr"
})
Of course! Little things that mean a lot in regex world
Thanks so much Sanford and hopefully this post helps a lot of people that are trying to figure out the same thing.