By Alvin Alexander. Last updated: August 28, 2019
I started using the Java FreeMarker template library recently, and I was surprised that it doesn’t return its output as a String by default. Skipping my angst over that, this code shows how to output FreeMarker results to a String:
// write the freemarker output to a StringWriter val stringWriter = new StringWriter template.process(data, stringWriter) // get the String from the StringWriter val string = stringWriter.toString
(That code is written in Scala, but as you can see, it converts easily to Java.)
The following complete FreeMarker example shows how this works:
import java.io._
import java.util._
import freemarker.template._
import scala.collection.JavaConversions._
import scala.collection.mutable.ArrayBuffer
object Test1 extends App {
val cfg = new Configuration
try {
val template = cfg.getTemplate("/Users/al/Projects/Scala/Tests/FreeMarkerTests/hello.ftl")
val data = scala.collection.mutable.Map[String, Object]()
data += ("message" -> "Hello, world!")
val countries = new ArrayBuffer[String]
countries += ("India")
countries += ("United States")
countries += ("Germany")
countries += ("France")
data.put("countries", countries)
// write to string
val output = new StringWriter
template.process(data, output)
val stringResult = output.toString
// do whatever you want/need to do with the string here ...
} catch {
case t: Throwable => //t.printStaceTrace
}
}
The source code for most of that class comes from this viralpatel.net link. I just added the part that shows how to output the FreeMarker template result as a String.

