FreeMarker Tutorial for Beginners

Introduction of FreeMarker Template (FTL)

Apache FreeMarker is a free Java-based template engine which focuses on MVC (Model View Controller) software architecture. The idea behind the using of MVC pattern for the dynamic Web Pages is to separate the designer form the programmer. FreeMarker is a general purpose template engine, and there is no dependency on servlet, HTML, or HTTP; thus, it can be used for the non-Web task as well. Although FreeMarker has some programming capabilities. Templates are written in FreeMarker Template Language (FTL), which is specialized and simple language (not a full-blown programming language like PHP). Usually, a general-purpose programming language (like java) prepares data to be displayed, and then, Apache FreeMarker is used to displays that prepared data using the template. It is a Java library to generate text output based on the template and changing data. Freemarker introduction In the template, we focused on How to present the data, and outside the template, we focused on what data to presents. Mostly it is used for the servlet-based web application development, and it can also be used for any kind of text output, i.e., generating CSS, java source code, etc. Freemarker templete

History of FreeMarker

FreeMarker had a tumultuous history until about 2004, because of the paradigm shifts and other significant changes on multiple occasions. Benjamin Geer and Mike Bayer wrote FreeMarker 1 (currently known as FreeMarker Classic, a separate project). From 2002, Jonathan Revusky was the new project lead, who released FreeMarker 2, which started the several substantial changes. FreeMarker was granted to the Apache Software Foundation in 2015, where it entered Apache Incubator. In 21-03-2018 it is fully accepted by the Apache project. The main goal of these changes was to make the template more strict, i.e., to detect many typos and typical mistakes as possible.  History of Freemarker       

Features of FreeMarker

Some features of FreeMarker are as follows - FreeMarker is powerful template language: Strings and arithmetic operations, conditional blocks, iterations and assignments, macros and functions, including other templates. FreeMarker has Versatile Data Model in Object wrapper: Through the pluggable adapters, java objects are exposed to the template as a tree of variable, which decides how the template sees them. FreeMarker has XML processing capabilities: It drops XML DOM-s into the data-model and traverses them or processes them. XML, ant support for the variable substitution. FreeMarker has localization and Internationalization: Locale sensitive number and date/time formatting. FreeMarker is multipurpose and light weighted: It has zero dependencies and any output format and can also be load from any place. Generic: Output goes to anywhere, and the dynamic template is loading by the FreeMarker engine. FreeMarker comes with built-in constructs in the template language to handle the typical web related tasks such as HTM –escaping.

Advantage of FreeMarker Template Engine

  • Separation of concern.
  • It avoids repetition of code.
  • Easier switching between views.
  • It provides reusability of code.
Template

Overall Structure of Freemarker

Templates are in fact program written in a programming language called FTL (FreeMarker Programming Language). It is a simple programming language which is designed for writing templates and nothing else. A template contains following these sections-
  • Text- Text which will be printed to the output as is.
  • Interpolation- This section value is replaced with the calculated value in the output. Interpolation is determined by } {and}. As we further discuss interpolation below.
  • FTL tags- FTL tags are a bit similar to the HTML tags, but they are instructions to the FreeMarker, and it will not be printed to the output.
  • Comments- Comments are also similar to the HTML comments, but they are delimited by the tag <# -- and -->. FreeMarker ignores comments, and it will not print in output.
Let's take an example of a concrete template. And we marked the template components with different colors like- text, interpolation, FTL and tags comments to visualize. Template
<# -- Greet the user by his/her name -->

Welcome }{user}!

We have these birds:
    <#list birds as bird>
  • }{bird.name} for }{bird.cost} dollar

FTL differentiate uppercase and lowercase letters. So, both list and List have different meaning. Similarly }{user} is not same as }{User} or }{USER}.
It is important to notice one thing about interpolation that it can be used in text only.
An FTL tag can't be used inside another FTL tags or inside the interpolation.
For Example-
<#if < include 'poo' > = 'jar'>... <#/if>
We can place comments inside the interpolation and in FTL tags. For Example-

Welcome }{user <# -- Name of user -->}

We have these birds:
    <#list <# -- Write comments here --> birds as <# -- again --> birds>
Example An example of FreeMarker is given below- Hello }{user}! You have this following messages: <#list messages as m> }{m.from}: }{m.body}


Output:-
Hello John! You have the following messages.
 Taylor:  Please don't forget to bring the papers of conference.
  Sandy:  Can you give me a visit today?
 Henry:  Don't forget the paper at this time.

The variable such as 'user' and 'messages' are coming from outside the template; so, template author has to deal only with the presentation issues. The template remains same if variables are coming from the database or from a cookie.
For Example-
These "Messages" is like a list or array of JavaBeans. It has two properties "from" and "body", but it might be something very different, and the template is not affected.
The } and curly braces {} is called interpolation. FreeMarker replace them in the output with the actual value of the things inside the curly brackets.
Interpolations : } {....}
It also does transformations as HTML-escaping, compression and syntax highlights, etc., on the output generated by the nested template fragments. We can define our transformations.  FreeMarker uses complex expressions to specify value everywhere.
  • Variable is accessed by its name like }{variable_name}
  • Arithmetic Operators, +,-,/,* e.g. {2+9/3}
  • Logical Operator &&,||,<= etc.
  • Sequence slice }{profile.assets[1...]}
  • Include files {include "header.html"}
  • Comment Section {#-- This is a comment--}
Basic Example Let's create a new java project com.vogella.freemarker.first, and create a new folder lib and add FreeMarker library to it. Add this library to the classpath for your project. If you have no idea how to achieve that, Please see the Eclipse IDE Tutorial for instruction. Create a new folder templates inside the com.vogella.freemarker.first package and create helloworld.ftl file inside it.

}{title}

}{exampleObject1.name1} by }{ExampleObject1.developer1}
    <#list systems as system>
  • }{system_index + 1}. }{system.name} from }{system.developer}

Now create the following class which demonstrates the usage of java objects in templates.
package com.vogella.freemarker.first;
public class valueExampleObject1{
private String name1, developer1;
public ValueExampleObject1(String name1, String developer1){
this.name1=name1;
this.developer1=developer1;
}
public String getName(){
return name1;
}
public String getDeveloper(){
return developer1;
}
}
Now create a class that creates the input for this template and also creates output.
package com.vogella.freemarker.first;
import java.io.File;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.Locale;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import freemarker.template.Version;
public class TestMainClass{
public static void main(String arg[]) throws Exception {
//Configure FreeMarker
// When the application starts, you should do this only ONCE
//and reuses the same configuration wherever needed.
Configuration cfg = new Configuration();
//some other recommended setting
Cfg.setIncompatibleImprovements(new version (3,4,20));
Cfg.setDefaultEncoding("UTF-8");
Cfg.setLocale(Locale.US);
//2 Process template
//2.1 Prepare the template input
Cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RTHROW_HANDLER);
Map <string, object=""> input= new HashMap <string, object="">();
Input.put("title", "Vogella Example");
Input.put("ExampleObject", new ValueExampleObject1("java object",  "me"));
List system = new ArrayList();
Systems.add(new ValueExampleObject1("Android", "Google");
Systems.add(new ValueExampleObject1("Ubuntu", "Canonical");
Systems.add(new ValueExampleObject1("IOS", "Apple");
Systems.add(new ValueExampleObject1("Windows", "Microsoft");
//2.2 Get the template
//Output on console
Template template = new Template("helloworld.ftl");
//2.3 Generate the output
Writer consoleWriter = new OutputStreamWriter(System.out);
template.process(input, consoleWriter);
// for the sake of example, write output into file
Writer fileWriter = new FileWriter(new File("output.html"));
try{
template.process(input, fileWriter);
}finally{
fileWriter.close();
}
}
}</string,></string,>

Download Maven

Apache FreeMarker is a template engine i.e., a java library to generate text output (HTML web pages, email, configuration files, and source code, etc.) based on template and changing data. Dependencies: FreeMarker has no dependencies, expect java itself with the minimum version indicated for each download. Backward compatibility: Before 2.3.0, releases with different second version numbers are not fully compatible. The series 2.3.x is quite conservative about backward compatibility; you are able to replace the FreeMarker binary (freemarker.jar) under your application with the newer one without breaking anything. Verifying Downloads: When downloading from a mirror, please check checksum and also verify OpenPGP compatible signature next to the download link. The public key used for signing. Latest version release: 2.3.28 on 04/04/2018

Installation of FreeMarker

Download the latest version of FreeMarker from the following webpage and add it to the classpath of your java project. https://freemarker.org/freemarkerdownload.html No real installation needs for FreeMarker. Just ensure that freemarker.jar is somewhere where your java applications class-loader will find it. In web application put freemarker.jar into the WEB-INF/lib directory of your web application. To use the certain optional FreeMarker features, the related party libraries have to available for the class-loader:
  • Jaxen and Apache Xalan are needed for XML path support. Use at least Jaxen 1.1-beta-8, not older version.
  • servlet classes are needed for FreeMarkerServlet.
  • You will need JSP 2.0 API or later available, for the custom JSP taglib support. No JSP implementation is required.
  • Jython 2.0 or later classes is needed for Jython wrapper.
  • Pre – 1.0 JDOM is needed for long deprecated freemarker.ext.jdom package.

Eclipse Integration

We can integrate FreeMarker with the eclipse. FreeMarker code completion and syntax highlighting is a part of JBoss tools. Add the following update site to your eclipse installation via Help > Install new Software. https://download.jboss.org/jbosstools/update/stable/kepler/ Eclipse Integration License: Apache FreeMarker is Java-based free software, licensed under the Apache License, Version 2.0.  You don't need to pay for this software.