FreeMarker example


Goal of this example

FreeMarker is a general purpose string templating engine. It is quite commonly used to generate HTML and it is well documented how to integrate it with spring as a view generator. This example shows how to use it directly.

Technology Used

  • FreeMarker 2.3.20
  • Spring 4.0.3.RELEASE
  • JUnit 4.8.1

Structure of the example project

The main interface of FreeMarker is Configuration that is responsible for

  • locating templates from file system, classpath, database or other location
  • handling encoding
  • combining parameters and template to produce output.

freemarker_overview

The below class shows how to configure a singleton FreeMarker “Engine” that loads template classes from classpath.

<pre>package org.exampledriven.freemarkerexample;

import freemarker.template.*;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.StringWriter;

@Component
public class FreeMarkerEngine {

    private Configuration configuration = new Configuration();

    public FreeMarkerEngine() {

        configuration.setClassForTemplateLoading(getClass(), "/");
        configuration.setObjectWrapper(new DefaultObjectWrapper());
        configuration.setDefaultEncoding("UTF-8");
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        configuration.setIncompatibleImprovements(new Version(2, 3, 20));

    }

    public String process(String templateName, Object model) {
        try {

            Template template = configuration.getTemplate(templateName);
            StringWriter stringWriter = new StringWriter();
            template.process(model, stringWriter);

            return stringWriter.toString();

        } catch (IOException | TemplateException e) {
            throw new RuntimeException(e);
        }
    }

}

Then as shown in FreeMarkerEngineTest it can be called as simple as this :

        Map<String, String> model = new HashMap<>();
        model.put("film_year", "1984");

        String result = freeMarkerEngine.process("sql/film.ftl", model);

FreeMarker directives

FreeMarker has a number of directives, most importantly it can include a template into another template using

<#include "film_subselect.ftl">

and it is possible to define conditional statements like this

<#if film_year??>

A full example is here

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: