SOLVED

Velocity email scripting - beginner's guide?

Go to solution
Anonymous
Not applicable

Hi everyone!

I'm starting to add email scripts in my emails and I'm looking for a guide for beginners, if this exists somewhere. I understand that Velocity is based on Java and that a Java guide could maybe help as well.

I'm trying to display text based on the Postal Code's first character:

#if(${lead.PostalCode}.substring(0, 0) == "H")

  #set($city = "Montreal")

#elseif(${lead.PostalCode}.substring(0, 0) == "M")

  #set($city = "Toronto")

#else

  #set($city = "your awesome city")

#end

${city}

This is raising an error, so I'm guessing the substring shouldn't be used this way. Any help will be greatly appreciated.

Thomas

1 ACCEPTED SOLUTION
SanfordWhiteman
Level 10 - Community Moderator

#if( $lead.PostalCode.startsWith("H") )

  #set( $city = "Montreal" )

#elseif( $lead.PostalCode.startsWith("M") )

  #set( $city = "Toronto" )

#else

  #set( $city = "your awesome city" )

#end

${city}

  • Don't bother with ${formal notation} in #set directives, where it isn't necessary, makes code harder to read, and can break stuff. You don't need {} here.
  • substring(0,0) means 0 characters starting from index 0. That's not going to match anything.
  • String objects have a startsWith() shortcut that returns a boolean, so you don't need to create a new string (which is what substring() does).

Also, think about moving to a collection-first approach as I describe here. With Velocity, organization is precious (it's not a particularly easy-to-read language, mostly because of the need to reduce whitespace).  So having all your "magic strings" at the top of a script is helpful. Like so:

#set( $pcInitialToCity_xref = {

  "H" : "Montreal",

  "M" : "Toronto",

  "" : "your awesome city"

} )

#set( $pcInitial = $lead.PostalCode.substring(0,1) )

#set( $city2 = $pcInitialToCity_xref[$pcInitial] )

#if( !$city2 )

  #set ( $city2 = $pcInitialToCity_xref[""] )## default

#end

${city2}

  • In this case, I do use substring() because I need that single-character string to do a property key lookup.

View solution in original post

19 REPLIES 19