Freemarker code snippets for Dialogue

 In Campaign automation, Content, Publishing, Reporting, Tips & Tricks

In Dialogue you can use the scripting language Freemarker to manipulate content and include the various available merge variables. You can find the full list of Freemarker built-ins here for reference. In this article we share some useful code examples to use in your content.

Contact fields and properties

There are many different merge variables available in Dialogue to use in sms and email content: contact fields, mail job fields, newsletter and article fields, placeholders for online view and webform links, and custom and pre-defined properties of various objects. You can find more details on where and how to use these on our support portal (login needed).

Examples for the different merge variable types
<!-- contact fields -->
<!-- contact fields -->
<!-- newsletter field -->
<!-- article fields -->
<!-- custom properties -->
Content edition: ${[key]}
Contact group: ${[key]}
Contact database: ${[key]}

Assigning variables

It’s often useful to assign variables to use elsewhere in your template or in Freemarker code. Variables can be assigned in the following ways:

Simple Assign
<#assign variable="value">
Assign multiple variables at once
<#assign variable1="value1" variable2="value2" variableX="valueX">
Extended assign
<#assign variable>
  The placeholder for this variable = ${variable}

Default value for merge fields

If a merge variable doesn’t always have a value, it’s necessary to prevent a publication error by providing a fallback, either by using ! followed by the default value (or an empty string, or simply nothing), or by using the has_content operator in an if-statement.

Default value using !
Dear ${contact.salutation!"sir/madam"} ${contact.lastname}
Shorthand for an empty string as the default value
Dear ${contact.firstname!}
Using has_content
<#if contact.music_preference?has_content>
  The latest ${contact.music_preference} records are available.
  The latest music is available at our stores.

Conditional statements: if, switch and hashes

Freemarker can be used to display content based on merge fields or other available variables. Apart from if-statements you could consider a switch statement when a condition has multiple values and each has a different outcome. A similar result can be reached by creating a hash with a key-value pair.

A typical if-statement
<#if contact.gender = "m">
  <p>Dear Mr. ${contact.lastname!}</p>
<#elseif contact.gender = "f">
  <p>Dear Ms. ${contact.lastname!}</p>
  <p>Dear sir/madam ${contact.lastname!}</p>
A switch statement
<#switch contact.gender >
  <#case "m">
    <p>Dear Mr. ${contact.firstname!} ${contact.lastname!}</p>
  <#case "f">
    <p>Dear Ms. ${contact.firstname!} ${contact.lastname!}</p>
    <p>Dear sir/madam ${contact.firstname!} ${contact.lastname!}</p>
Hash with key-value pair
<#assign salutation = {"f":"madam", "m":"sir", "n":"sir/madam"}>

<!--contact.gender(key) determines which value is set for salutation-->
Dear ${salutation[contact.gender]} ${contact.lastname}

Click here for the Freemarker built-ins for hashes.

Date and time values

The variables .now and currentdate.datetime each return the current date-time and can be converted to a date or a time value. You will often want to assign this value for further operations, like using one of the various Freemarker built-in operators for dates and times to convert the value to text. You can use a locale setting to regionalize the output of the built-ins (make sure to use <#noparse>for the locale if it involves contact date fields in a newsletter). For more details check out this article on our support portal (login needed).

The .now variable
${.now}       --> Nov 27, 2019 3:21:18 PM
${.now?date}  --> Nov 27, 2019
${.now?time}  --> 3:21:18 PM
<!-- currentdate.datetime is the name as .now -->
${currentdate.datetime} --> Nov 27, 2019 3:21:18 PM
Assign the datetime to a variable
<#assign currentDateTime = .now>
${currentDateTime}	--> Nov 27, 2019 3:21:18 PM

<#assign currentDate = currentDateTime?date>
${currentDate}		--> Nov 27, 2019

<#assign currentTime = currentDateTime?time>
${currentTime}		--> 3:21:18 PM
Convert date and time values to a string
{(contact.lastopendate?string("dd MMMM yyyy"))!"No field value"}
--> 10 May 2019

{(contact.lastclickdate?string.medium)! }
--> Apr 20, 2020

<!—from string to date to string-->
${'12-18-2018'?date("MM-dd-yyyy")?string("MMMM yyyy")}
--> December 2018
Use the locale setting to localize
<!-- use noparse around the locale setting for contact date fields in a newsletter -->
<#setting locale="nl_NL">

${(contact.lastopendate?string("dd MMMM yyyy"))!}
--> 10 mei 2019

<!-- from string to date to string-->
${'12-05-2018'?date("MM-dd-yyyy")?string("MMMM yyyy")}
--> mei 2018

In Dialogue you can use the following 2 custom date functions: addDays to add a number of days to a date value and substractDates to find the difference between 2 dates.

Custom date function addDays
<!-- use addDays always in conjunction with a ?string operator -->
Tomorrow: ${addDays(.now, 1)?string("dd-MM-yyyy")}<br>
Next week: ${addDays(.now, 7)?string("dd-MM-yyyy")}<br>
Next year: ${addDays(.now, 365)?string("dd-MM-yyyy")}<br>
Custom function substractDates
<#assign targetdate = '2019-12-31'?date("yyyy-MM-dd")>
<#assign daysleft = substractDates(.now, targetdate)>

<!-- raw value -->
${daysleft} --> TimeDifference [years=0, days=24, hours=592, minutes=35579, seconds=2134752, timeStamp=Sat Jan 24 16:59:12 CET 1]

<!-- extract years, days, hours, minutes or seconds -->
There are ${daysleft.days} days left until NYE!

Online view link

There are several ways to include the online view link in emails. The easiest one is the placeholder (see the first snippet), but for a stylable link you can use one of other options. If you use these in a newsletter you need to use <#noparse> because the links contain the contactId.

Full online view link options
1.	https://td[##]${contact.encryptedContactId}&mid=${contact.encryptedJobId}
2.	https://td[##]${contact.encryptedJobId}/${contact.encryptedContactId}/view.html
3.	https://td[##]${contact.contactId}&jobId=${contact.jobId}
Use !onlineViewer to hide the link in the online view version
<#if !onlineViewer>
Is this email not displaying correctly? <a href="https:// td[##]${contact.contactId}&jobId=${contact.jobId}" target="_blank" style="text-decoration:underline; color:#000000;">View it in your browser</a>

Importing external data

External data from an HTML source
<#assign content = webImporter("")>
External data from an XML source
<#assign content = xmlImporter("")>
  <#list as item>
External data from a JSON source
<#assign jsonfeed = jsonImporter(" ","3")/>
<#list jsonfeed as feeditem> 

Various useful Freemarker snippets

Declare #ftl to use square brackets instead of angle brackets for Freemarker

[#assign salutation = "Dear reader"]
${salutation}, after declaring [#ftl] in your template all freemarker tags should be wrapped in [] instead of <>
Using image attributes
<img src="${newsimg.url}" alt="${newsimg.title}" title="${newsimg.title}" height="${newsimg.height}" width="${newsimg.width}" />

<!-- in an if-statement -->
<#if image.width < 340>image too small</#if>
Using the ?then operator as a more flexible Boolean operator
<#assign x = 10>
<#assign y = 20>

<!-- use x in case of true and y for false -->
${100 + (x > y)?then(x, y)} outputs = 120

You can find more information on the ?then operator here.

Recent Posts