Back to blog

FreeMarker in HTML templates: commands and practical examples

Martin Pecho
Martin Pecho

One HTML template can create a personal greeting, hide an unnecessary section, build a table with any number of items, and format an amount or a date. Apache FreeMarker provides the FTL language for writing these rules directly in the template. This practical guide shows which commands to use and how they change what the recipient sees in the email.

An HTML template and input data pass through FreeMarker to create a personalized email.

How to write expressions in an HTML template

doMail executes template commands on the server when generating a message. The email client receives the finished HTML. Conditions determine the email content before it is sent. For example, a discount notice appears only for customers who meet the specified condition. The recipient then receives the completed content.

We use four basic forms of syntax when writing a template. Each serves a different purpose:

  • Insert a value — ${...}. For example, ${CustomerName} is replaced with the customer name in the email.
  • Transform a value — ?operation_name. Add the operation after a value or variable name. For example, ${CustomerName?upper_case} displays the name in uppercase, while ${12.56?round} displays the rounded number 13.
  • Control the content — <#...>. The <#if ...> directive decides whether a block appears, <#list ...> repeats it for list items, and <#assign ...> stores a value in a variable.
  • Call a macro — <@... />. A macro is a named block prepared for reuse, such as a footer or button. Use <@macroName /> to insert it where needed.

The reference tables use FTL syntax directly. Variable names must match the template data, including uppercase and lowercase letters. Some examples define their own values with assign. Others use the input object shown in the data section. Each explanation identifies the values needed for its example.

There are two ways to add HTML to the visual editor:

  • Upload a complete HTML file. If you already have a complete template, use the HTML button in the Graphic design section and upload the file.
  • Insert or edit code in the editor. Open the three-dot menu and select the <> button labeled Source code. In the window that opens, you can insert HTML or edit the existing template code. Confirm the changes and save the template.

Uploading a file is useful for a complete template. To add a condition, adjust a greeting, or make another small change, you can use Source code directly.

A directive is a command that controls how template content is generated. For example, <#if ...> starts a condition, <#else> provides alternative content, and <#list ...> repeats a block for individual items. The directive itself is not displayed to the recipient; the email contains the content produced by its instructions.

Write directives inside HTML comments <!-- ... --> so the editor preserves them. Replace the characters < and > with &lt; and &gt;. For example, store <#if CustomerName?has_content> as <!-- &lt;#if CustomerName?has_content&gt; -->. Expressions that insert values, such as ${CustomerName}, go directly in the HTML.

The following example displays a personal greeting using the value of CustomerName when the name is filled in; otherwise, it displays “Hello!”. The outputformat and autoesc blocks select HTML output and ensure that special characters in inserted values appear as text:

<div>
  <!-- &lt;#outputformat "HTML"&gt; -->
  <!-- &lt;#autoesc&gt; -->
  <!-- &lt;#if CustomerName?has_content&gt; -->
  <p>Hello ${CustomerName}!</p>
  <!-- &lt;#else&gt; -->
  <p>Hello!</p>
  <!-- &lt;/#if&gt; -->
  <!-- &lt;/#autoesc&gt; -->
  <!-- &lt;/#outputformat&gt; -->
</div>

Before evaluating the template, doMail converts &lt; and &gt; back to < and >. Commands therefore run even when stored inside HTML comments. A comment written this way does not disable the command.

A template header is the opening <#ftl ...> declaration. It can configure how the template is processed, including the output format and automatic escaping. It does not appear in the resulting email.

The header is optional. If used, <#ftl ...> must be at the beginning of the FTL template so its settings apply when the content is parsed. The visual editor may add its own HTML before the inserted content, so this example selects HTML output with an outputformat block, which can also appear inside the template.

Quick recipe: rounding and displaying amounts

To display numbers using US English conventions, set locale before inserting the values. Numeric literals in the code and text converted with ?number use a decimal point.

<#setting locale="en_US">

On mobile, swipe the tables sideways to see the full expression and its result.

TaskSyntaxResult
Nearest whole number ?round rounds to the nearest whole number. For example, 1.4 → 1 and 1.5 → 2. The result is a number.${12.56?round}13
Round down to a whole number ?floor always rounds down to a whole number. For example, 1.9 → 1. The result is a number.${12.56?floor}12
Round up to a whole number ?ceiling always rounds up to a whole number. For example, 1.1 → 2. The result is a number.${12.01?ceiling}13
Round a value to two decimal places The calculation rounds the value to two decimal places. The final ?c produces a plain numeric representation with a decimal point, regardless of the locale.${((12.567 * 100)?round / 100)?c}12.57
Display two decimal places ?string("0.00") creates text with two decimal places. It does not change the original numeric variable. Complete calculations before formatting.${12.5?string("0.00")}12.50
Display one decimal place ?string("0.0") creates text with one decimal place. Formatting may use a different rounding rule from ?round for exact halfway values.${12.56?string("0.0")}12.6
Amount with currency The amount is displayed with two decimal places, followed by EUR. For accounting amounts, follow the calculation and rounding rules supplied by the application.${12.5?string("0.00")} EUR12.50 EUR
Percentage The format 0% displays a proportion as a percentage with no decimal places: 0.2 becomes 20%. The result is text.${0.2?string("0%")}20%
Price from CSV text UnitPrice is loaded from Source data. In this example, it contains the text "12.5". The ?number operation converts it to a number, which we multiply by two.${(UnitPrice?number * 2)?string("0.00")}25.00

Data, conditions, and repeating content

Suppose the input contains the following object:

{
  "CustomerName": "John",
  "customer": {"CustomerName": "John"},
  "emptyCustomer": {"CustomerName": ""},
  "OrderStatus": "paid",
  "Quantity": 2,
  "UnitPrice": "12.5",
  "Fee": 1,
  "n": 3,
  "items": ["A", "B", "C"],
  "shortItems": ["A", "B"],
  "numbers": [1, 2],
  "emptyItems": []
}

The fields of this object represent the data available to the template when doMail generates a message. The top-level field CustomerName contains “John”. The nested object customer has its own field with the same name and value, accessed as customer.CustomerName. The emptyCustomer object exists, but its name is an empty string, "". The guest object and phone field are deliberately absent so we can demonstrate how to handle missing data. The price UnitPrice is the string "12.5", which we convert to a number before calculating.

How to choose content using a condition

Conditions let us adapt an email to the data of a particular customer. For a customer who has paid, we can display a payment acknowledgment. For someone whose payment is still outstanding, we can send a reminder instead. Both messages can be prepared in one template, and doMail selects the appropriate one when generating the email.

Write this decision using if, elseif, and else. After if, specify the condition to check, followed by the content to display when it is true. If the first condition is false, elseif can check another one. For example, after checking for payment, we might check whether the order was canceled. Put content for all remaining cases in else. Once a matching branch is selected, the remaining branches in that decision are skipped.

When choosing between specific values of one field, such as an order status, we can use switch. Prepare separate content for each status so paid, unpaid, and canceled orders can have different messages. Conditions can also compare numbers. The operator gt means “greater than” and lt means “less than”. If amount contains the order total, amount gt 100 is true when the total exceeds 100.

What to display when data is missing

When creating a greeting, we need to know whether the customer name is available. In these examples, the name is represented by CustomerName. Two different situations are possible: the variable does not exist, or it exists but contains an empty string, "". The expression CustomerName?? checks only whether the variable exists. If it exists but is empty, the check still returns true. To check whether the name also has content, use CustomerName?has_content.

The ! operator provides a fallback when a variable is missing. The complete expression for inserting the value into an email is ${CustomerName!"Guest"}. Read it as: “Display the value of CustomerName. If that variable does not exist, display Guest instead.” If the variable contains John, the recipient sees “John”. If it is missing, the recipient sees “Guest”.

If CustomerName exists but contains an empty string, "", the ! operator does not use the fallback. For an empty name, use ?has_content to choose between a personal greeting and a general one.

A name can also contain only spaces, which count as content. First use ?trim to remove spaces from the beginning and end, then check whether any content remains. If the name is in a nested object, such as customer.CustomerName, parentheses matter too. The expression (customer.CustomerName)!"Guest" uses the fallback when the name is missing or when the entire customer object is missing.

How to repeat content for list items

The number of items in an order varies, so we do not need to prepare every table row separately. With list, we define what one row should look like, and doMail repeats it for each item in the input list. An order with two items produces two rows, while an order with five items produces five. Each row uses the data of its own item, such as its name, quantity, and price.

Sometimes we want to display names next to each other, separated by commas. The sep directive inserts a comma or another separator only between items, leaving nothing extra after the last item. To number the rows, use ?counter: it returns 1 for the first item, 2 for the second, and so on. The ?index value also identifies an item position, but starts at zero: the first item has index 0 and the second has index 1.

If the list has no items, else within list can display a message such as “The order contains no items” instead of a table. We can also interrupt a loop while it runs. The break directive ends the loop completely, so no further items are processed. The continue directive skips the remaining content for the current item and moves to the next one. This can exclude an item that should not appear in the final overview.

The following expressions use the input object above. The i icon explains which values each row uses and how they produce the stated result.

FunctionSyntaxResult
Interpolation and nested data The input object customer contains CustomerName with the value “John”. The expression ${customer.CustomerName} reads that name and inserts it into the greeting. Inserting a value into text this way is called interpolation. The email displays “Hello John!”.
Hello ${customer.CustomerName}!
Hello John!
Missing values and parentheses The guest object is absent from the input. Parentheses allow a fallback even when the entire object is missing, so the ! operator displays “Guest”. If guest existed and contained a name, that name would appear instead. The ! operator alone does not replace an existing empty string.
${(guest.CustomerName)!"Guest"}
Guest
Existence versus content The phone field is missing, so phone?? returns false. The name in emptyCustomer is empty, so ?has_content also returns false. The name in customer contains “John”, so its check returns true. The ?c operation displays boolean values as true and false. The | character separates the results.
${(phone??)?c}|${emptyCustomer.CustomerName?has_content?c}|${customer.CustomerName?has_content?c}
false|false|true
Fallback for an empty name The input contains emptyCustomer, but its CustomerName is an empty string. The ?has_content condition is false, so the personal name is not displayed. The else branch displays “Guest”. This handles an empty name, for which the ! operator alone would not use a fallback.
<#if emptyCustomer.CustomerName?has_content>${emptyCustomer.CustomerName}<#else>Guest</#if>
Guest
Conditions, logic, and comparison The input provides n = 3. The expression n gt 2 checks whether it exceeds 2, and n lt 5 checks whether it is below 5. The && operator requires both conditions to be true. They are, so the result is “YES”. The elseif and else branches are skipped. The == operator checks equality.
<#if n gt 2 && n lt 5>YES<#elseif n == 2>TWO<#else>NO</#if>
YES
Multiple switch cases The input field OrderStatus contains "paid". The switch directive compares it with the values after case. It matches “paid”, so “Paid” appears and break ends the selection. The default branch displays “Other status” if no prepared case matches.
<#switch OrderStatus><#case "paid">Paid<#break><#default>Other status</#switch>
Paid
Variables and arithmetic We read Quantity = 2, UnitPrice = "12.5", and Fee = 1 from the input. Since the price is text, ?number converts it to a number. The calculation 2 × 12.5 + 1 = 26 is stored in total. The second expression, 7 % 3, returns the remainder after division: 1. The | character separates the results, and ?c produces plain numeric output.
<#assign total=Quantity * UnitPrice?number + Fee>${total?c}|${(7 % 3)?c}
26|1
List items with separators The input field items is a list containing A, B, and C. The list directive goes through the list and makes the current item available as x. The expression ${x} displays it. The sep directive adds a comma and space between items, with no separator after the last one. The result is “A, B, C”.
<#list items as x>${x}<#sep>, </#list>
A, B, C
Empty list with else The input field emptyItems contains [], an empty list. There are no items for list to display, so it uses the content after else: “No items”. Here, else belongs to list and appears only when the list is empty.
<#list emptyItems as x>${x}<#else>No items</#list>
No items
Index, position, and first/last item We use the input list shortItems, containing A and B. Four values appear for each item: ?index is its position from 0, ?counter counts from 1, ?is_first checks for the first item, and ?is_last checks for the last. A produces 0:1:true:false and B produces 1:2:false:true. Colons separate values for one item; | separates the items.
<#list shortItems as x>${x?index?c}:${x?counter?c}:${x?is_first?c}:${x?is_last?c}<#sep>|</#list>
0:1:true:false|1:2:false:true
Alternating rows and the next item The input list numbers contains 1 and 2. The ?item_cycle operation selects “odd” for the first item and “even” for the second. These are chosen labels that can be used, for example, as CSS row classes. The ?has_next operation checks whether another item follows: true for the first and false for the last. The colon and | separate the results.
<#list numbers as x>${x?item_cycle("odd","even")}:${x?has_next?c}<#sep>|</#list>
odd:true|even:false
Nested loops The outer list takes A and B from shortItems. For each letter, the inner list goes through numbers, containing 1 and 2. This produces A1 and A2 first, then B1 and B2. The inner sep separates pairs with commas, while the outer one separates groups with |.
<#list shortItems as a><#list numbers as b>${a}${b?c}<#sep>,</#list><#sep>|</#list>
A1,A2|B1,B2
Ranges, break, and continue This row creates a numeric range directly with 1..5. Within the loop, n is the current item, rather than the input value n. The number 1 appears. At 2, continue skips the rest of that iteration, so 2 does not appear. The number 3 appears. At 4, break ends the loop. With no separator, the displayed numbers form “13”.
<#list 1..5 as n><#if n == 2><#continue></#if><#if n == 4><#break></#if>${n?c}</#list>
13
List wrapper with items The list directive uses the input list shortItems, containing A and B. The items directive marks the content to repeat for each item. The square brackets are outside that repeated content, so they appear only once. Inside, A and B are separated by a comma, producing “[A,B]”. The same structure can put a whole list inside one HTML wrapper.
<#list shortItems>[<#items as x>${x}<#sep>,</#items>]</#list>
[A,B]

Text operations and regular expressions

Text from Source data may contain extra spaces, an overly long name, or information from which we need only one part. We can adjust it directly in the template before inserting it into an email. For example, we can display a name in uppercase, extract a number from an order identifier, or shorten a product name to make it easier to read.

How to remove spaces and change letter case

The ?trim operation removes spaces from the beginning and end of text. It is useful when, for example, an unwanted space appears before a customer name. Spaces between words remain unchanged. To adjust repeated spaces inside the text as well, use ?replace, which replaces matching text with another value. Use ?upper_case to convert the entire text to uppercase and ?lower_case to convert it to lowercase.

How to extract or shorten text

To extract particular characters, we need their positions in the text. A position is called an index, and counting starts at zero. In DOMAIL, D has index 0, O has index 1, and M has index 2. The expression ${"DOMAIL"?substring(0, 2)} starts at the first character and stops before index 2, producing DO. The expression ${"DOMAIL"[0..2]} includes the character at index 2 and therefore produces DOM.

Use ?truncate to shorten a long name. Along with the target length, specify a marker that indicates the text has been shortened, such as three dots. The marker counts toward the resulting length. Thus, ${"ABCDEFGHIJ"?truncate(7, "...")} produces ABCD...: four letters and three dots make seven characters.

How to find text using a pattern

We do not always need to find a particular word or an exact value. Sometimes we need to check whether a value contains only digits or find the numeric part of an identifier. A regular expression is a pattern that describes the characters we are looking for. For example, [0-9]+ means one or more digits. The ?matches operation checks whether the entire text matches the pattern. The text 12345 matches, but A12B does not because it also contains letters.

We can also use a pattern with ?replace. Add the "r" parameter to enable regular expression matching. The expression ${"A12B"?replace("[0-9]+", "#", "r")} finds the numeric part 12 and replaces it with #, so the email displays A#B. Without "r", it would look for the literal text [0-9]+ rather than a sequence of digits.

FunctionSyntaxResult
Trim and letter case The first expression removes leading and trailing spaces and changes doMail to DOMAIL. The second changes DOMAIL to lowercase. The third capitalizes only the first letter of the name, producing John smith. The | character separates the results.
${"  doMail  "?trim?upper_case}|${"DOMAIL"?lower_case}|${"john smith"?cap_first}
DOMAIL|domail|John smith
Length and text slices DOMAIL has 6 characters. The operation substring(0,2) selects positions 0 and 1, producing DO. The slice [2..] starts at M in position 2 and continues to the end, producing MAIL.
${"DOMAIL"?length?c}|${"DOMAIL"?substring(0,2)}|${"DOMAIL"[2..]}
6|DO|MAIL
Searching text We check whether doMail contains Mail, starts with do, and ends with Mail. All three conditions hold, so true appears three times. These checks are case-sensitive.
${"doMail"?contains("Mail")?c}|${"doMail"?starts_with("do")?c}|${"doMail"?ends_with("Mail")?c}
true|true|true
Replace, split, and join The first expression replaces every a with X, producing X-b-X. The second splits a,b,c at the commas into three items, then joins them with / . The result is a / b / c.
${"a-b-a"?replace("a","X")}|${"a,b,c"?split(",")?join(" / ")}
X-b-X|a / b / c
Text before and after a separator The operation ?keep_before("-") extracts the text before the hyphen: ORD. The operation ?keep_after("-") extracts the text after it: 42. The | character separates the results.
${"ORD-42"?keep_before("-")}|${"ORD-42"?keep_after("-")}
ORD|42
Regular expressions The pattern [0-9]+ means one or more digits. The whole text 12345 matches, so the first expression returns true. The second finds 12 in A12B and replaces it with #, producing A#B. The "r" parameter enables regular expression matching.
${"12345"?matches("[0-9]+")?c}|${"A12B"?replace("[0-9]+","#","r")}
true|A#B
Shortening and padding text The operation ?truncate(7,"...") shortens the text to seven characters including the three dots, producing “ABCD...”. The operation ?left_pad(5,"0") adds three zeros before 42 to make five characters: 00042.
${"ABCDEFGHIJ"?truncate(7,"...")}|${"42"?left_pad(5,"0")}
ABCD...|00042
Normalizing spaces First, ?trim removes spaces at the beginning and end. Then ?replace uses the pattern " +" to replace each sequence of spaces with one space. Only one space remains between A and B. The "r" parameter enables regular expression matching.
${"  A   B  "?trim?replace(" +"," ","r")}
A B

Numbers, calculations, and boolean values

Calculations require numbers, but a price loaded from CSV may be stored as text, such as "12.5". Convert it to a number with ?number before multiplication or addition. If the text may have spaces at either end, remove them first with ?trim. Combine the operations as UnitPrice?trim?number. This conversion uses a decimal point; text that is not a valid number causes an error.

Calculating a value and displaying it are separate tasks. First calculate the amount, then format it as the text the recipient should see. For example, ?string("0.00") displays two decimal places. With locale="en_US", the decimal separator is a point. The format "#,##0.00" also adds grouping separators, as in 1,234.50. For locale-independent numeric output without grouping separators or unnecessary trailing zeros, use ?c.

A boolean value has two possibilities: true means a condition holds, and false means it does not. The text "true" in source data is not yet a boolean; convert it with ?boolean. For display, use ?c to output true or false, or choose readable labels such as “yes” and “no” with ?string. The ?then operation selects one of two values according to the boolean condition.

FunctionSyntaxResult
Numeric text from CSV We use UnitPrice, which contains the text "12.5" in the example input. The ?trim operation removes any spaces at either end, and ?number converts the text to a number. The price for two units is 12.5 × 2 = 25. The ?c operation displays the resulting number.
${(UnitPrice?trim?number * 2)?c}
25
Number formatting and locale The setting locale="en_US" selects US English number formatting. The pattern "#,##0.00" adds a thousands separator and two decimal places, so 1234.5 appears as 1,234.50. Formatting produces text.
<#setting locale="en_US">${1234.5?string("#,##0.00")}
1,234.50
Plain numeric output The ?c operation displays 1234.5 without grouping separators or added zeros, regardless of the locale. Use it when further processing needs a consistent plain numeric representation.
<#setting locale="en_US">${1234.5?c}
1234.5
Rounding and absolute value From left to right, ?round rounds 2.6 to 3, ?floor rounds 2.6 down to 2, and ?ceiling rounds 2.1 up to 3. The ?abs operation returns the absolute value of −3, which is 3. The | character separates the results.
${2.6?round?c}|${2.6?floor?c}|${2.1?ceiling?c}|${(-3)?abs?c}
3|2|3|3
Booleans and text selection The first expression displays the boolean true. The second uses false, so it selects the second of “yes” and “no”: “no”. The third uses true, so ?then selects the first option, “A”. The results are separated by |.
${true?c}|${false?string("yes","no")}|${true?then("A","B")}
true|no|A
Converting text to a boolean The values "true" and "false" are written as text. The ?boolean operation converts them to boolean values. Then ?c displays them as true and false.
${"true"?boolean?c}|${"false"?boolean?c}
true|false
Currency and percentage formatting With the chosen locale, 12.5 is displayed with two decimal places as 12.50, followed by EUR. The pattern "0%" displays the proportion 0.2 as 20%. Both formatting operations produce text.
<#setting locale="en_US">${12.5?string("0.00")} EUR|${0.2?string("0%")}
12.50 EUR|20%

Dates, time, and localization

FunctionSyntaxResult
Date from input text The operation ?date("yyyy-MM-dd") reads the input text as year, month, and day. Then ?string("dd MMM yyyy") selects the display format, producing 30 Nov 2026. Here, yyyy is the year, MM the numeric month, MMM the abbreviated month name, and dd the day. The locale setting determines the language of month names.
${"2026-11-30"?date("yyyy-MM-dd")?string("dd MMM yyyy")}
30 Nov 2026
Time and date-time The first expression reads 13:05:09 and displays it without seconds as 13:05. The second reads a date and time and displays 30 Nov 2026 13:05. The pattern HH means hours in 24-hour format, mm minutes, and ss seconds. Case matters: MM is a month, while mm is minutes. The | character separates the results.
${"13:05:09"?time("HH:mm:ss")?string("HH:mm")}|${"2026-11-30 13:05"?datetime("yyyy-MM-dd HH:mm")?string("dd MMM yyyy HH:mm")}
13:05|30 Nov 2026 13:05
Time zone and ISO input The final Z in the input means the time is in UTC. The operation ?datetime.iso reads the ISO timestamp. The setting time_zone="Europe/Bratislava" selects local time in Bratislava for display. On this date, 12:00 UTC therefore appears as 13:00.
<#setting time_zone="Europe/Bratislava">${"2026-11-30T12:00:00Z"?datetime.iso?string("HH:mm")}
13:00
Current date and time The special variable .now provides the current date and time when the message is generated. The pattern controls its appearance, and time_zone controls the time zone used for display. The table shows an example; the actual current value is used when the template runs. For an order date or invoice issue date, use the relevant field from Source data.
${.now?string("dd MMM yyyy HH:mm")}
e.g. 30 Nov 2026 14:24
ISO date format The setting time_zone="UTC" selects UTC when reading the date. The ?date operation converts text to a date, and ?iso_utc displays it in the ISO year-month-day format. The result is 2026-11-30.
<#setting time_zone="UTC">${"2026-11-30"?date("yyyy-MM-dd")?iso_utc}
2026-11-30

Lists, sorting, filtering, and transforming data

FunctionSyntaxResult
Size, first item, and last item The assign directive creates xs with the values 3, 1, and 2. The ?size operation returns the item count, 3. The ?first operation selects the first value, 3, and ?last selects the last value, 2. The | character separates the three results.
<#assign xs=[3,1,2]>${xs?size?c}|${xs?first?c}|${xs?last?c}
3|3|2
Sort, reverse, and slice The first expression sorts the numbers in ascending order as 1,2,3. The second reverses its input list [1,2,3] to produce 3,2,1. The third selects positions 0 and 1, producing 1,2. The ?join operation joins items with commas. Numbers loaded as CSV text need conversion before numeric sorting.
${[3,1,2]?sort?join(",")}|${[1,2,3]?reverse?join(",")}|${[1,2,3][0..1]?join(",")}
1,2,3|3,2,1|1,2
Sorting objects by a key Each object has a field n, containing B in the first object and A in the second. The operation ?sort_by("n") sorts by this field, placing A first. The list directive displays x.n. With no separator, the result is AB.
<#list [{"n":"B"},{"n":"A"}]?sort_by("n") as x>${x.n}</#list>
AB
Searching a list The operation ?seq_contains("B") checks whether B is in the list and returns true. The operation ?seq_index_of("B") returns its position. Counting starts at zero, so A is at position 0 and B at position 1. The result is true|1.
${["A","B"]?seq_contains("B")?c}|${["A","B"]?seq_index_of("B")?c}
true|1
Chunking items into rows The operation ?chunk(2) splits the list into groups of up to two items. It produces 1,2 and a second group containing only 3. Items within a group are joined with commas, and groups are separated by |. The result is 1,2|3. The same grouping can be used to build rows containing multiple products.
<#list [1,2,3]?chunk(2) as row>${row?join(",")}<#sep>|</#list>
1,2|3
Filter with a lambda expression The expression x -> x gt 2 defines a condition for each item, where x is its value. The ?filter operation keeps only numbers greater than 2: 3 and 4. The operation ?join(",") combines them into 3,4.
${[1,2,3,4]?filter(x -> x gt 2)?join(",")}
3,4
Map with a lambda expression The expression x -> x * 2 multiplies each item, represented by x, by two. The ?map operation turns 1,2,3 into 2,4,6. Then ?join(",") combines them into 2,4,6.
${[1,2,3]?map(x -> x * 2)?join(",")}
2,4,6
Take while and drop while Both operations start with the first item and check “less than 3”. The ?take_while operation keeps the initial 1,2 and stops at 3; it never includes the final 1. The ?drop_while operation skips the initial 1,2, stops skipping at 3, and keeps the remaining 3,1.
${[1,2,3,1]?take_while(x -> x lt 3)?join(",")}|${[1,2,3,1]?drop_while(x -> x lt 3)?join(",")}
1,2|3,1

Maps, dynamic keys, and type checks

What a map is and how to read a value

A map is an object that stores values under particular names. These names are called keys. In customer, for example, CustomerName is a key and “John” is the value stored under it. The expression ${customer.CustomerName} finds that field and displays its value: the customer name.

Sometimes the name of the field we want is stored in another variable rather than written directly in the expression. This is a dynamic key. If key contains "CustomerName", the expression ${customer[key]} first reads that variable and then uses its value to find the field in customer. The result is again “John”. Square brackets therefore let us select a field using a name that can change.

How to get keys, values, and individual entries

In the first table row, we create a simple map h containing {"b":2,"a":1}. Its keys are b and a. The value stored under b is 2, and the value under a is 1. When key contains "a", ${h[key]} selects 1. If we store "b" in key, the same expression selects 2.

Use ?keys to get a list of the map keys and ?values to get a list of its values. Here, these are the names a and b and the numbers 1 and 2. To display them in a particular order, sort each list with ?sort and join it into text with ?join. To process each key together with its value, use list with two variables. In as k,v, k contains the key and v its value. We can display them together as, for example, a=1.

The + operator can combine two maps. A map containing a and a map containing b become one map containing both entries. We can combine lists in the same way: [1] and [2] become [1,2].

How to check a value type

Before using a value, it can be helpful to check what kind of data it contains. The number 12 and the text "12" may look the same in an email, but behave differently in calculations. The ?is_number operation checks for a number, while ?is_string checks for text. Similarly, ?is_sequence identifies a list, ?is_hash a map, and ?is_boolean a boolean.

A type check returns true if the value has the requested type, or false otherwise. It does not change the type. The text "12", for example, remains text after a check; use ?number to convert it to a number. In the last table row, each value has the type being checked, so true appears five times.

FunctionSyntaxResult
Map, dynamic key, and keys The map h contains the keys b and a, with values 2 and 1. The variable key contains “a”, so h[key] selects 1. The ?keys operation gets the keys, and ?values gets the values. Each list is sorted independently and joined with commas. The result contains 1, a,b, and 1,2 in that order.
<#assign h={"b":2,"a":1}><#assign key="a">${h[key]?c}|${h?keys?sort?join(",")}|${h?values?sort?join(",")}
1|a,b|1,2
Iterating over key/value pairs The list directive goes through both map entries. The variable k contains the key and v its value. Together they are displayed as a=1 and b=2. The sep directive inserts | between these pairs.
<#list {"a":1,"b":2} as k,v>${k}=${v?c}<#sep>|</#list>
a=1|b=2
Combining maps and lists The + operator first combines two maps into one containing a and b. The expression h.b selects 2. The second part combines [1] and [2] into [1,2]. The operation ?join(",") displays those items separated by a comma.
<#assign h={"a":1}+{"b":2}>${h.b?c}|${([1]+[2])?join(",")}
2|1,2
Type checks We check whether “x” is text, 1 is a number, [] is a list, {} is a map, and true is a boolean. Each value has the requested type, so true appears five times. Empty lists and maps still have a type; these checks do not check whether they contain items.
${"x"?is_string?c}|${1?is_number?c}|${[]?is_sequence?c}|${{}?is_hash?c}|${true?is_boolean?c}
true|true|true|true|true

Macros, custom functions, and reusable blocks

FunctionSyntaxResult
Macro and named parameters A macro is a named content block that can be inserted repeatedly. The macro hello prepares a greeting and accepts CustomerName. We pass “John” when calling it, so it displays Hello John!. The value “Guest” in the definition is the default, used if the parameter is omitted.
<#macro hello CustomerName="Guest">Hello ${CustomerName}!</#macro><@hello CustomerName="John" />
Hello John!
Nested macro content The macro box provides a reusable wrapper. The nested directive inserts the content written between the opening and closing tags of the macro call. We pass “Content”, which is inserted between square brackets to produce [Content]. This structure can wrap custom content in a prepared HTML block.
<#macro box>[<#nested>]</#macro><@box>Content</@box>
[Content]
Function, local variable, and return A function returns a value that can be used elsewhere. We pass a price of 10 and a rate of 0.2 to gross. The local directive stores 10 × (1 + 0.2), or 12, in result. That variable belongs only to the current function call. The return directive returns the calculated value, and the final expression displays it.
<#function gross price rate><#local result=price * (1 + rate)><#return result></#function>${gross(10,0.2)?c}
12
Capturing generated content The assign block stores the prepared greeting in greeting. Its content is not displayed at this point. The following expression ${greeting} inserts the saved content into the email, displaying Hello John.
<#assign greeting>Hello John</#assign>${greeting}
Hello John
Removing extra whitespace The compress directive reduces repeated whitespace in its content. One space remains between A and B. A line break remains between B and C because the original whitespace included a line break. It does not necessarily put all output on one line. A line break in HTML source alone does not create a visible line break in an email; use <br> for that.
<#compress>A   B
   C</#compress>
A B
C
Omitting an FTL comment An FTL comment stores notes for the template author. Text between <#-- and --> is omitted from the resulting email. Only A and B remain in this example, joined without a space as AB.
A<#-- hidden comment -->B
AB

HTML escaping and building URLs

Each example below assumes HTML output with automatic escaping enabled. Text such as <b>A & B</b> should appear as text unless it is explicitly intended to be trusted HTML. The ?esc operation escapes a value according to the output format, while ?no_esc allows a ready-made HTML fragment. Use it only for content whose source and HTML you control.

The Result column shows what the recipient sees in the email. In the first three rows, HTML tags appear as plain text. With ?no_esc, the tags apply formatting, so OK appears in bold. HTML escaping does not validate the destination URL. The ?url("UTF-8") operation encodes a parameter value; applying it to a complete URL would encode its separators too.

FunctionSyntaxResult
Automatic HTML escaping
${"<b>A & B</b>"}
Escaping quotation marks
${'"A" & <B>'}
Explicit esc without double escaping
${"<b>A</b>"?esc}
Trusted HTML with no_esc
${"<strong>OK</strong>"?no_esc}
UTF-8 URL parameter
${"A B&č"?url("UTF-8")}
A%20B%26%C4%8D
URL path preserving slashes
${"a/b c"?url_path("UTF-8")}
a/b%20c

Evaluating text and handling errors

Sometimes a calculation or part of a template is stored as text. For example, ?eval evaluates the text "1 + 2" to produce the number 3. The ?interpret operation turns text into a template fragment that we can call like a macro. When it runs, embedded expressions such as the customer name are evaluated too.

If an error occurs while generating optional content, attempt and recover can provide a fallback. In the example, "abc" cannot be converted to a number, so prepared alternative text appears instead. These directives do not repair an incorrectly written template; they handle errors that occur during execution.

Use ?eval and ?interpret only with command text you have prepared yourself. Do not execute ordinary customer data or arbitrary CSV content as code. The i icons explain each example.

FunctionSyntaxResult
Evaluating an expression from text The value "1 + 2" starts as text. The ?eval operation reads it as an expression and calculates 3. Then ?c displays the number. Without evaluation, the text itself would appear as 1 + 2.
${"1 + 2"?eval?c}
3
Running text as a template The text contains a greeting with ${CustomerName}. The prefix r preserves that expression without immediately inserting the name. The ?interpret operation creates a template fragment stored as part. When called, it uses the input name “John” and displays Hello John!.
<#assign part=r"Hello ${CustomerName}!"?interpret><@part />
Hello John!
Fallback content on error The attempt block tries to convert "abc" to a number. That conversion fails, so recover runs and displays “Fallback content”. This can provide a readable alternative when an optional content block fails.
<#attempt>${"abc"?number}<#recover>Fallback content</#attempt>
Fallback content
Evaluating only the selected option The condition is true, so ?then selects the first option, “OK”. The second option, optionalValue, is not evaluated, so that variable does not need to exist for this condition. If the condition were false, the second option would be used and optionalValue would need to exist.
${true?then("OK",optionalValue)}
OK
Output format and automatic escaping The special variable .output_format returns the current output format, here HTML. The variable .auto_esc reports whether inserted values are escaped automatically. The ?c operation displays that boolean as true. This expression lets the author inspect the template settings.
${.output_format}|${.auto_esc?c}
HTML|true

For a complete example of connecting CSV data, building an item table, and calculating a total, see Dynamic email tables.