Anthony Johnson - 2011-08-12

Hey folks,

When I started using Freemarker, learning was difficult as I couldn't easily apply a template.

I wrote a quick Java class to apply a template and thought this might help anyone new to Freemarker.

Compile the class into a jar file and execute using:

java –jar fmapply.jar <ftl file> <xml file> <output file>

Note: Use full file paths.

I hope this helps someone sometime.

Thanks,

Anthony.

import freemarker.ext.dom.NodeModel;
import freemarker.template.Template;
import freemarker.template.Configuration;
import freemarker.cache.*;
import java.io.OutputStreamWriter;
import java.io.FileOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class fmapply
{
public static void main(String args)
{
Map<String, NodeModel> tree = new HashMap<String, NodeModel>();

File fTemplate = new File(args); // Free Marker template File
File fDocument = new File(args); // XML file
File fOutput = new File(args); // Output file

// Read the XML file and process the template using FreeMarker
try {
tree.put("doc", freemarker.ext.dom.NodeModel.parse(fDocument));
freemarkerDo(tree, fTemplate, fOutput);
}
catch(Exception e) {
System.out.println(e.getLocalizedMessage());
}
}

// Process a template using FreeMarker and print the results
static void freemarkerDo(Map<String, NodeModel> datamodel, File fTemplate, File fOutput) throws Exception
{
File fParent = new File(fTemplate.getParent());
Configuration configuration = new Configuration();
FileTemplateLoader templateLoader = new FileTemplateLoader(fParent);
configuration.setTemplateLoader(templateLoader);
Template tpl = configuration.getTemplate(fTemplate.getName());
OutputStreamWriter output = new OutputStreamWriter(new FileOutputStream(fOutput));
tpl.process(datamodel, output);
output.close();
}
}