Java Freemarker Templates (FTL) Tutorial with HTML Example

By Arvind Rai, October 10, 2015
This page will walk through java Freemarker templates (FTL) tutorial with HTML example. Freemarker is an open source powerful template language. It has versatile data model. We can use Freemarker templates for different purposes like generating HTML files, emails, source code etc. Here we will provide a Freemarker template demo to generate a HTML file for a blog step by step.

Freemarker Templates

Freemarker Templates can generate HTML, email, source code, configuration files etc as an output. We need to create a template using Freemarker template language that is also known as FTL. While creating template, we combine our hard coded values and Freemarker code. To use Freemarker, we use syntax as
My Name: ${name}
 
In our example, we will generate an HTML code using Freemarker template language.

Resolve Freemarker JAR Dependency using Gradle

Find the gradle build file to resolve Freemarker JAR dependency.
build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'Concretepage'
version = '1.0-SNAPSHOT' 
repositories {
    maven { url "https://repo.spring.io/libs-release" }
    mavenLocal()
    mavenCentral()
}
dependencies {
    compile 'org.freemarker:freemarker:2.3.23'
} 

Project Structure in Eclipse

Find the project structure in eclipse.
Java Freemarker Templates  (FTL) Tutorial  with HTML Example

Create HTML Template using Freemarker Template Language

In our example we are creating a HTML template for a blog. This template will generate HTML output with title, body message and reference URLs.
D:\ftl\blog-template.ftl
<html>
<head><title> ${blogTitle} </title>
<body>
<h1> ${blogTitle} </h1>
<p>
  ${message}
</p>
<h3>References</h3>
<#list references as reference>
    ${reference_index + 1}. <a href="${reference.url}"> ${reference.title} </a> <br/>
</#list>
</body>
</html> 

Create Configuration Instance

To run the Freemarker template code, first we will create Freemarker Configuration instance that is singleton class.
Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
cfg.setDirectoryForTemplateLoading(new File("D:/ftl"));
cfg.setDefaultEncoding("UTF-8");
cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);  
Here we set Freemarker version, location of FTL file, default encoding etc.

Create a Data Model with Java Bean

To create a data model, we are using a java Map with String and Object data type. We will create our java bean to hold the values. The Map key must match with Freemarker template variables.
Map<String, Object> map = new HashMap<>();
map.put("blogTitle", "Freemarker Template Demo");
List<URL> references = new ArrayList<>();
references.add(new URL("http://url1.com","URL One")); 
We are using following java bean in our example.
URL.java
package com.concretepage;
public class URL {
	private String url;
	private String title;
	public URL(String url, String title) {
		this.url = url;
		this.title = title;
	}
	public String getUrl() {
		return url;
	}
	public void setUrl(String url) {
		this.url = url;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
} 

Instantiate the Template

Now instantiate Freemarker Template with our template file as follows.
Template template = cfg.getTemplate("blog-template.ftl");
 
The given template file will be searched in the location configured in Configuration instance.

Process Data Model to generate Output in File and Console

Template has a method as
Template.process(Object dataModel, Writer out)
 
that process data model in desired output target. To generate output in console, write code as following.
Writer console = new OutputStreamWriter(System.out);
template.process(map, console); 
To generate code in a file, we can do as follows.
Writer file = new FileWriter (new File("D:/ftl/blog-template-output.html"));
template.process(map, file); 

Main Class with Complete Code

Find the Main class to run our demo.
FTLBlog.java
package com.concretepage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
public class FTLBlog {
      public static void main(String[] args) {
         try {
            //Instantiate Configuration class  
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_23);
            cfg.setDirectoryForTemplateLoading(new File("D:/ftl"));
            cfg.setDefaultEncoding("UTF-8");
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            //Create Data Model
            Map<String, Object> map = new HashMap<>();
            map.put("blogTitle", "Freemarker Template Demo");
            map.put("message", "Getting started with Freemarker.<br/>Find a simple Freemarker demo.");
            List<URL> references = new ArrayList<>();
            references.add(new URL("http://url1.com","URL One"));
            references.add(new URL("http://url2.com","URL Two"));
            references.add(new URL("http://url3.com","URL Three"));
            map.put("references", references);
            //Instantiate template
            Template template = cfg.getTemplate("blog-template.ftl");
            //Console output
            Writer console = new OutputStreamWriter(System.out);
            template.process(map, console);
            console.flush();
            // File output
            Writer file = new FileWriter (new File("D:/ftl/blog-template-output.html"));
            template.process(map, file);
            file.flush();
            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
      }
} 

HTML Output

The output in console and in given html file(D:/ftl/blog-template-output.html) will be as following.
<html>
<head><title> Freemarker Template Demo </title>
<body>
<h1> Freemarker Template Demo </h1>
<p>
  Getting started with Freemarker.<br/>Find a simple Freemarker demo.
</p>
<h3>References</h3>
    1. <a href="http://url1.com"> URL One </a> <br/>
    2. <a href="http://url2.com"> URL Two </a> <br/>
    3. <a href="http://url3.com"> URL Three </a> <br/>
</body>
</html> 

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us