Newlines to <BR>s in Velocity

When you output a textarea token in an HTML email, you might be surprised that its linebreaks go bye-bye. This really should be expected, as newlines are typically swallowed in HTML unless you have specifically ordered otherwise.

One fix is to use a CSS white-space style override:

<div style="white-space: pre-line;">{{lead.myTextareaField}}</div>

I believe that style is honored in all modern mail clients, but you've required the email author to remember to always wrap that token in certain formatting. Better, I'd think, to give them a token that's already HTML-aware.

What you want, then, is a token with all the newlines (ASCII 10 or ASCII 13 + 10, represented as \n or \r\n in regex matches) converted to HTML <BR> tags.

Taking into account some quirks of Velocity, the tightest effective VTL I've found to do this is:

#define( $nl2br )
## keep current newline for readability, prepend BR
${output.replaceAll("\r?\n", "<BR>$0")}##
#end
#set( $output = $lead.myTextareaField )
${nl2br}

Let me know how it works out for you!