Using FreeMarker with Ant
There are two ``FreeMarker Ant tasks'' that we know about:
-
FreemarkerXmlTask: It comes with the FreeMarker distribution, packed into the freemarker.jar. This is a lightweight, easy-to-use Ant task for transforming XML documents with FreeMarker templates. Its approach is that the source files (input files) are XML files, which are rendered to corresponding output files, by a single template. That is, for each XML file, the template will be executed (with the XML document in the data-model), and the template output will be written into a file of similar name than the name of the XML file. Thus, the template file plays a similar role as an XSLT style sheet, but it is FTL, not XSLT.
-
FMPP: It's a more heavyweight, less XML centric, third party Ant task (and standalone command-line tool). Its primary approach is that the source files (input files) are template files that generate the corresponding output files themselves, but it also supports the approach of FreemarkerXmlTask for the source files that are XML-s. Also, it has extra features over the FreemarkerXmlTask. What's its drawback then? As it is more complex and more generalized, it's harder to learn and use it.
This section introduces the FreemarkerXmlTask. For more information about FMPP visit its homepage: http://fmpp.sourceforge.net/.
In order to use the FreemarkerXmlTask, you must first define the freemarker.ext.ant.FreemarkerXmlTask inside your Ant buildfile, then call the task. Suppose you want to transform several XML documents to HTML using the hypothetical "xml2html.ftl" template, with XML documents located in the directory "xml" and HTML documents generated into directory "html". You would write something like:
| |||
The task would invoke the template for every XML document. Every document would be parsed into a DOM tree, then wrapped as a FreeMarker node variable. When template processing begins, the special variable, .node, is set to the root node of the XML document.
Note that if you are using the legacy (FreeMarker 2.2.x and earlier) XML adapter implementation, that still works, and the root of the XML tree is placed in the data-model as the variable document. That contains an instance of the legacy freemarker.ext.xml.NodeListModel class.
Note that all properties defined by the build file would be made available as a hash model named "properties". Several other models are made available; for detailed description of what variables are made available to templates as well as what other attributes can the task accept, see the JavaDoc for freemarker.ext.ant.FreemarkerXmlTask.