Module freemarker
ballerinax/freemarker Ballerina library
1.0.0
Overview
The ballerinax/freemarker library provides a Ballerina interface to Apache FreeMarker, a Java-based template engine for generating text output (HTML, email, configuration files, source code, etc.) from templates and data.
Key Features
- Render FreeMarker templates from inline strings using structured Ballerina data
- Load and render FreeMarker templates from
.ftlfiles on the filesystem - Full support for FreeMarker template syntax including variable interpolation, conditionals (
<#if>), and iteration (<#list>) - Pass any
record {|json...;|}map directly as the template data context
Quickstart
Add the import
import ballerinax/freemarker;
Render a template string
Use freemarker:render to process an inline FreeMarker template:
import ballerinax/freemarker; import ballerina/io; public function main() returns error? { string template = "Hello, ${name}! You have ${count} new messages."; string result = check freemarker:render(template, {"name": "Alice", "count": 5}); io:println(result); // Output: Hello, Alice! You have 5 new messages. }
Render a template from a file
Use freemarker:renderFromFile to load and process a .ftl template file:
import ballerinax/freemarker; import ballerina/io; public function main() returns error? { map<json> data = { "customerName": "Bob", "orderId": "ORD-001", "items": [ {"name": "Widget", "qty": "2", "unitPrice": "9.99"} ], "total": "19.98" }; string result = check freemarker:renderFromFile("templates/invoice.ftl", data); io:println(result); }
FreeMarker template syntax
FreeMarker templates use ${...} for variable interpolation, <#if> for conditionals, and <#list> for iteration:
Dear ${customerName}, Your order ${orderId} is confirmed. Items purchased: <#list items as item> ${item.name} — Qty: ${item.qty} @ $${item.unitPrice} </#list> Order total: $${total} <#if isPremiumMember?? && isPremiumMember> Thank you for being a Premium member! </#if>
API
render
public isolated function render(string template, record {|json...;|} data) returns string|Error
Renders a FreeMarker template string with the provided data context.
template(string) — FreeMarker template stringdata(record {|json...;|}) — Key-value pairs used as the data context- return (
string|Error) — Rendered string output, or anErroron failure
renderFromFile
public isolated function renderFromFile(string templatePath, record {|json...;|} data) returns string|Error
Renders a FreeMarker template loaded from a file.
templatePath(string) — Path to the.ftltemplate filedata(record {|json...;|}) — Key-value pairs used as the data context- return (
string|Error) — Rendered string output, or anErroron failure
Examples
The examples directory contains practical use cases:
- Order confirmation email — Generates a formatted order confirmation email using variable interpolation, list iteration, and conditional blocks.
Import
import ballerinax/freemarker;Other versions
1.0.0