What is FreeMarker ?

FreeMarker                   

FreeMarker is a Java-based template engine focusing on the MVC software architecture. Although it’s mostly used for Servlet-based Web Application development, it can be used for any other kind of text output, such as generating CSS, Java source code, etc. Unlike JSP, it is not dependent on the Servlet architecture or on HTTP. Thus it can be used for non-Web tasks as well. FreeMarker is Free software.
It is a dynamic “On the Fly” template based text output rendering “language” which can output text in various formats. It is thus highly suitable wherever there is a need to customize the output in various formats and dynamically.

Template + Data model  = Output text

FreeMarker is designed to be practical for the generation of HTML Web pages, particularly by servlet-based applications following the MVC (Model View Controller) pattern. The idea behind using the MVC pattern for dynamic Web pages is that you separate the designers (HTML authors) from the programmers. Everybody works on what they are good at. Designers can change the appearance of a page without programmers having to change or recompile code, because the application logic (Java programs) and page design (FreeMarker templates) are separated.
Templates do not become polluted with complex program fragments. This separation is useful even for projects where the programmer and the HTML page author is the same person, since it helps to keep the application clear and easily maintainable.

FreeMarker
FreeMarker

 
FreeMarker is not a Web application framework. It is suitable as a component in a Web application framework, but the FreeMarker engine itself knows nothing about HTTP or servlets. It simply generates text. As such, it is perfectly usable in non-web application environments as well. Note, however, that we provide out-of-the-box solutions for using FreeMarker as the view component of Model 2 frameworks (e.g. Struts), which also let you use JSP taglibs in the templates.

Built-ins for strings

Boolean

The string converted to boolean value. The string must be true or false (case sensitive!), or must be in the format specified by the boolean_format setting.
If the string is not in the appropriate format, an error will abort template processing when you try to access this built-in.

cap_first

The string with the very first word of the string capitalized. For the precise meaning of “word” see the word_list built-in.
Example:
${”  green mouse”?cap_first}${“GreEN mouse”?cap_first}${“- green mouse”?cap_first}
The output:
Green mouseGreEN mouse- green mouse
In the case of “- green mouse”, the first word is the -.

Capitalize

The string with all words capitalized. For the precise meaning of “word” see the word_list built-in.
Example:
${”  green  mouse”?capitalize}${“GreEN mouse”?capitalize}
The output:
Green MouseGreen Mouse

chop_linebreak

The string without the line-break at its very end if there was a line-break, otherwise the unchanged string.

Contains

Returns if the substring specified as the parameter to this built-in occurs in the string.
For example:
<#if “piceous”? contains(“ice”)>It contains “ice”</#if>
This will output:
It contains “ice”

ends_with

Returns whether this string ends with the substring specified in the parameter.
For example:
“ahead”? ends_with (“head”) returns Boolean true. Also, “head”? ends_with (“head”) will return true.

ensure_ends_with

If the string doesn’t end with the substring specified as the 1st parameter, it adds it after the string, otherwise it returns the original string.
For example:
both “foo”? ensure_ends_with(“/”) and “foo/”?ensure_ends_with(“/”) returns “foo/”
 

Built-ins for numbers

abs

Gives the absolute value of a number.
For example:
x? abs , if x is -5, will evaluate to 5..

is_infinite

Tells if a number is floating point infinite (according to IEEE 754).
For example:
some Number? Is_infinite evaluates to true or false depending on if the value of some Number is infinite or not. Of course, if the underlying number is not of floating point type, this will always return false.

is_nan

Tells if a number is floating point NaN (according to IEEE 754).
For example:
some Number? is_nan evaluates to true or false depending on if the value of some Number is NaN or not. Of course, if the underlying number is not of floating point type, this will always return false.
round, floor, ceiling
Converts a number to a whole number using the specified rounding rule:

  • Round : Rounds to the nearest whole number. If the number ends with .5, then it rounds                                             upwards (i.e., towards positive infinity)
  • Floor : Rounds the number downwards (i.e., towards negative infinity)
  • Ceiling : Rounds the number upwards (i.e., towards positive infinity)

upper_abc
Same as lower_abc, but converts to upper case letters, like “A”, “B”, “C”, …, “AA”, “AB”, etc.
 
Built-ins for date/time/date-time values
 
date, time, datetime (when used with a date/time/date-time value)
These built-ins can be used to specify which parts of the date-like variable are in use:

  • Date : Date only, no time of the day.
  • Time : Only the time of the day, no date part
  • Datetime : Both date and time

date_if_unknown, time_if_unknown, datetime_if_unknown
The date_if_unknown, time_if_unknown, datetime_if_unknown built-ins mark a date-like value with some of the sub-types: date without time, time, or date-time, respectively.
However, if the value already holds this information, the built-in has no effect. That is, it will never convert the sub-type of a value, it only adds the sub-type if it was unknown.
Built-ins for booleans

c (when used with boolean)

This built-in converts a boolean to string for a “computer language” as opposed to for human audience. The result will be “true” or “false”, regardless of the boolean_format setting. When generating JavaScript and such, this should be used, as otherwise changing the boolean_format can break the generated computer-language output.

then

Used like Boolean Exp? then (when Truewhen False), fills the same role as the ternary operator in C-like languages (i.e., Boolean Exp ? when True : when False). If Boolean Exp evaluates to boolean true then it evaluates and returns its first argument, or else if Boolean Exp evaluates to boolean false then it evaluates and return its second argument.
Off course, all three expressions can be arbitrary complex. The argument expressions can have any type, even different types.

Built-ins for sequences

first

The first subvariable of the sequence. Template processing will die with error if the sequence is empty.
Join
Concatenates the items of a sequence to a single string, with the given separator.
For example:
<#assign colors = [“red”, “green”, “blue”]>${colors?join(“, “)}
output:
red, green, blue
Last
The last subvariable of the sequence. Template processing will die with error if the sequence is empty.

Reverse

The sequence with reversed order.

Size

The number of sub variables in sequence (as a numerical value). The highest possible index in sequence s is s? size – 1 (since the index of the first subvariable is 0) assuming that the sequence has at least one subvariable.

Sort

Returns the sequence sorted in ascending order. (For descending order use this and then the reverse built in.) This will work only if all sub variables are strings, or if all sub variables are numbers, or if all sub variables are date values (date, time, or date+time), or if all sub variables are booleans (since 2.3.17). If the sub variables are strings, it uses locale (language) specific lexical sorting (which is usually not case sensitive).
For example:
<#assign ls = [“whale”, “Barbara”, “zeppelin”, “aardvark”, “beetroot”]?sort><#list ls as i>${i} </#list>
Will print (with US locale at least):
aardvark Barbara beetroot whale zeppelin

Built-ins for hashes

Keys

A sequence that contains all the lookup keys in the hash. Note that not all hashes support this (ask the programmer if a certain hash allows this or not).
<#assign h = {“name”:”mouse”, “price”:50}><#assign keys = h?keys><#list keys as key>${key} = ${h[key]}; </#list>
Output:
name = mouse; price = 50;

values

A sequence that contains all the variables in the hash. Note that not all hashes support this (ask the programmer if a certain hash allows this or not).

Features

A few highlights of FreeMarker:

  • Powerful template language : Conditional blocks, iterations, assignments, string and arithmetic operations and formatting, macros and functions, including other templates, and many more
  • Multipurpose and lightweight : Zero dependencies, any output format, can load templates from any place (pluggable), many configuration options
  • Internationalization/localization-aware : Locale sensitive number and date/time formatting localized template variations.
  • XML processing capabilities : Drop XML DOM-s into the data-model and traverse them, or even process them declaratively
  • Versatile data-model : Java objects are exposed to the template as a tree of variables through pluggable object wrappers, which decides how the template sees them.