# FreeMarker Manual

For FreeMarker 2.3.19

## Preface

### What is FreeMarker?

FreeMarker is a template engine: a generic tool to generate text output (anything from HTML to autogenerated source code) based on templates. It's a Java package, a class library for Java programmers. It's not an application for end-users in itself, but something that programmers can embed into their products.

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.

Although FreeMarker has some programming capabilities, it is not a full-blown programming language like PHP. Instead, Java programs prepare the data to be displayed (like issue SQL queries), and FreeMarker just generates textual pages that display the prepared data using templates.

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 such as Struts.

FreeMarker is Free, released under a BSD-style license. It is OSI Certified Open Source Software. OSI Certified is a certification mark of the Open Source Initiative.

### What should I read?

If you are a ...

- designer, then you should read the and then you can look into the on an as-needed basis for more specific details.

- programmer, then you should read the guide first, then the and then you can look into the on an as-needed basis for more specific details.

### Document conventions

Variable names, template fragments, Java class names, etc. are written like this: `foo`.

If something should be replaced with a concrete value then it is written in italics, as follows: `Hello yourName!`.

Template examples are written like this:

    something

Data-model examples are written like this:

    something

Output examples are written like this:

    something

Program examples are written like this:

    something

This paragraph is for the editors, and not visible for the public

In chapters this section is for the editors toowritten for both designers and programmers fragments addressed to programmers are written like this: This is for programmers only.

New terms are emphasized like this: some new term

### Contact

For the latest version of FreeMarker and to subscribe to the mailing lists visit the FreeMarker homepage:

If you need help or you have suggestions, use the mailing lists (mail archives can be searched without subscription) or the Web based forums. If you want to report a bug, use the Web based bug tracker, or the mailing lists. To find all of these visit . Also, note that we have a FAQ and index; use them.

help
homepage
download
contact

### About this document

If you find any mistakes (including grammatical mistakes, typos, typographical mistakes) or you find something misleading or confusing in the documentation, or you have other suggestions, please let me know! Email: ddekany at users.sourceforge.net

## Template Author's Guide

### Getting Started

This chapter is a very rough introduction to FreeMarker. The chapters after this will go over things in much greater detail. Nonetheless, once you have read this chapter, you will be able to write simple but useful FreeMarker templates.

#### Template + data-model = output

Assume you need a HTML page in an e-shop application, similar to this:

    <html>
    <head>
      <title>Welcome!</title>
    </head>
    <body>
      <h1>Welcome Big Joe!</h1>
      <p>Our latest product:
      <a href="products/greenmouse.html">green mouse</a>!
    </body>
    </html>

Let's say that the user name ("Big Joe" above) should depend on who the logged in Web page visitor is, and the latest product should come from a database and thus it potentially changes at any moment. In this situation you can't just enter the user name nor the URL and name of the latest product into the HTML, you can't use static HTML.

FreeMarker's solution for this problem is using a template instead of the static HTML. The template is the same as the static HTML, except that it contains some instructions to FreeMarker that makes it dynamic:

    <html>
    <head>
      <title>Welcome!</title>
    </head>
    <body>
      <h1>Welcome ${user}!</h1>
      <p>Our latest product:
      <a href="${latestProduct.url}">${latestProduct.name}</a>!
    </body>
    </html>

The template is stored on the Web server, usually just like the static HTML page would be. But whenever someone visits this page, FreeMarker will step in and transform the template on-the-fly to plain HTML by replacing the `${...}`-s with up-to-date content (e.g., replacing `${user}` with Big Joe or whoever the visitor is) and send the result to the visitor's Web browser. So the visitor's Web browser will receive something like the first example HTML (i.e., plain HTML without FreeMarker instructions), and it will not perceive that FreeMarker is used on the server. The template file itself (which is, again, stored on the Web server) is not changed during this, so the transformation will happen again and again for each visiting. This ensures that the displayed information is always up-to-date.

Now, you already may have noticed that the template contains no instructions regarding how to find out who the current visitor is, or how to query the database to find out what the latest product is. It seems it just already know these values. And indeed that's the case. An important idea behind FreeMarker (actually, behind Web MVC) is that presentation logic and "business logic" should be separated. In the template you only deal with presentation issues, that is, visual design issues, formatting issues. The data that will be displayed (such as the user name and so on) is prepared outside FreeMarker, usually by routines written in Java language or other general purpose language. So the template author doesn't have to know how these values are calculated. In fact, the way these values are calculated can be completely changed while the templates can remain the same, and also, the look of the page can be completely changed without touching anything but the template. This separation can be especially useful when the template authors (designers) and the programmers are different individuals.

While for FreeMarker (and for the template author) it's not interesting how the data was calculated, FreeMarker still have to know what the actual data is. All the data that the template can use is packed into the so called data-model. It's created by the already mentioned routines that calculate the data. As far as the template author is concerned, the data-model is a tree-like structure (like folders and files on your hard disk), that in this case could be visualized as:

data-model

    (root)
      |
      +- user = "Big Joe"
      |
      +- latestProduct
          |
          +- url = "products/greenmouse.html"
          |
          +- name = "green mouse"

(To prevent misunderstandings: The data-model is not a text file, the above is just a visualization of a data-model for you. It's from Java objects, but let that be the problem of the Java programmers.)

Compare this with what you seen in the template earlier: `${user}` and `${latestProduct.name}`. As an analogy, the data model is something like the file system of computers: the root and `latestProduct` correspond to directories (folders) and the `user`, `url` and `name` correspond to files. `url` and `name` are in the `latestProduct` directory. So `latestProduct.name` is like saying `name` in the `latestProduct` directory. But as I said, it was just a simile; there are no files or directories here.

To recapitulate, a template and a data-model is needed for FreeMarker to generate the output (like the HTML shown first):

Template + data-model = output

#### The data-model at a glance

As you have seen, the data-model is basically a tree. This tree can be arbitrarily complicated and deep, for example:

    (root)
      |
      +- animals
      |   |
      |   +- mouse
      |   |   |
      |   |   +- size = "small"
      |   |   |
      |   |   +- price = 50
      |   |
      |   +- elephant
      |   |   |
      |   |   +- size = "large"
      |   |   |
      |   |   +- price = 5000
      |   |
      |   +- python
      |       |
      |       +- size = "medium"
      |       |
      |       +- price = 4999
      |
      +- test = "It is a test"
      |
      +- whatnot
          |
          +- because = "don't know"

The variables that act as directories (the root, `animals`, `mouse`, `elephant`, `python`, `whatnot`) are called hashes. Hashes store other variables (the so called subvariables) by a lookup name (e.g., "animals", "mouse" or "price").

The variables that store a single value (`size`, `price`, `test` and `because`) are called scalars.

When you want to use a subvariable in a template, you specify its path from the root, and separate the steps with dots. To access the `price` of a `mouse`, you start from the root and go into `animals`, and then go into `mouse` then go into `price`. So you write `animals.mouse.price`. When you put the special `${...}` codes around an expression like this, you are telling FreeMarker to output the corresponding text at that point.

There is one more important kind of variable: sequences. They are similar to hashes, but they don't store names for the variables they contain. Instead, they store the subvariables sequentially, and you can access them with a numerical index. For example, in this data-model, `animals` and `whatnot.fruits` are sequences:

    (root)
      |
      +- animals
      |   |
      |   +- (1st)
      |   |   |
      |   |   +- name = "mouse"
      |   |   |
      |   |   +- size = "small"
      |   |   |
      |   |   +- price = 50
      |   |
      |   +- (2nd)
      |   |   |
      |   |   +- name = "elephant"
      |   |   |
      |   |   +- size = "large"
      |   |   |
      |   |   +- price = 5000
      |   |
      |   +- (3rd)
      |       |
      |       +- name = "python"
      |       |
      |       +- size = "medium"
      |       |
      |       +- price = 4999
      |
      +- whatnot
          |
          +- fruits
              |
              +- (1st) = "orange"
              |
              +- (2nd) = "banana"

To access a subvariable of a sequence you use a numerical index in square brackets. Indexes start from 0 (it's a programmer tradition to start with 0), thus the index of the first item is 0, the index of the second item is 1, and so on. So to get the name of the first animal you write `animals[0].name`. To get the second item in `whatnot.fruits` (which is the string `"banana"`) you write `whatnot.fruits[1]`.

Scalars can be further divided into these categories:

- String: Text, that is, an arbitrary sequence of characters such as ''m'', ''o'', ''u'', ''s'', ''e'' above. For example the `name`-s and `size`-s are strings above.

- Number: It's a numerical value, like the `price`-s above. The string `"50"` and the number `50` are two totally different things in FreeMarker. The former is just a sequence of two characters (which happens to be readable as a number for humans), while the latter is a numerical value that you can use, say, in arithmetical calculations.

- Date/time: A date or time. Like the date an animal were captured, or the time the shop opens.

- Boolean: A true/false (yes/no, on/off, etc.) thing. Like animals could have a `protected` subvariable, which store if the animal is protected or not.

Summary:

- The data-model can be visualized as a tree.

- Scalars store a single value. The value can be a string or a number or a date/time or a boolean.

- Hashes are containers that store other variables and associate them with a unique lookup name.

- Sequences are containers that store other variables in an ordered sequence. The stored variables can be retrieved via their numerical index, starting from 0.

#### The template at a glance

The simplest template is a plain HTML file (or whatever text file -- FreeMarker is not confined to HTML). When the client visits that page, FreeMarker will send that HTML to the client as is. However if you want that page to be more dynamic then you begin to put special parts into the HTML which will be understood by FreeMarker:

- `${...}`: FreeMarker will replace it in the output with the actual value of the thing inside the curly brackets. They are called interpolations. As an example see the very first example.

- FTL tags (for FreeMarker Template Language tags): FTL tags are a bit similar to HTML tags, but they are instructions to FreeMarker and will not be printed to the output. The name of these tags start with `#`. (User-defined FTL tags use `@` instead of `#`, but they are an advanced topic.)

- Comments: Comments are similar to HTML comments, but they are delimited by `<#--` and `-->`. Anything between these delimiters and the delimiter itself will be ignored by FreeMarker, and will not be written to the output.

Anything not an FTL tag or an interpolation or comment is considered as static text, and will not be interpreted by FreeMarker; it is just printed to the output as is.

With FTL tags you refer to so-called directives. This is the same kind of relationship as between HTML tags (e.g.: `<table>` and `</table>`) and HTML elements (e.g., the `table` element) to which you refer to with the HTML tags. (If you don't feel this difference then just take "FTL tag" and "directive" as synonyms.)

##### Examples of directives

Though FreeMarker has far more directives, in this quick overview we will only look at three of the most commonly used ones.

###### The if directive

With the `if` directive you can conditionally skip a section of the template. For example, assume that in the very first example you want to greet your boss, Big Joe, differently from other users:

    <html>
    <head>
      <title>Welcome!</title>
    </head>
    <body>
      <h1>
        Welcome ${user}<#if user == "Big Joe">, our beloved leader</#if>!
      </h1>
      <p>Our latest product:
      <a href="${latestProduct.url}">${latestProduct.name}</a>!
    </body>
    </html>

Here you have told FreeMarker that the '', our beloved leader'' should be there only if the value of the variable `user` is equal to the string `"Big Joe"`. In general, things between `<#if condition>` and `</#if>` tags are skipped if `condition` is false (the boolean value).

Let's detail the `condition` used here: The `==` is an operator that tests if the values at its left and right side are equivalent, and the results is a boolean value, true or false accordingly. On the left side of `==` I have referenced a variable with the syntax that should be already familiar; this will be replaced with the value of the variable. In general, unquoted words inside directives or interpolations are treated as references to variables. On the right side I have specified a literal string. Literal strings in templates must always be put inside quotation marks.

This will print "Pythons are free today!" if their price is 0:

    <#if animals.python.price == 0>
      Pythons are free today!
    </#if>

Similarly as earlier when a string was specified directly, here a number is specified directly (`0`). Note that the number is not quoted. If you quoted it (`"0"`), FreeMarker were misinterpret it as a string literal.

This will print "Pythons are not free today!" if their price is not 0:

    <#if animals.python.price != 0>
      Pythons are not free today!
    </#if>

As you may have guessed, `!=` means not equivalent.

You can write things like this too (using the data-model used to demonstrate hashes):

    <#if animals.python.price < animals.elephant.price>
      Pythons are cheaper than elephants today.
    </#if>

With the `<#else>` tag you can specify what to do if the condition is false. For example:

    <#if animals.python.price < animals.elephant.price>
      Pythons are cheaper than elephants today.
    <#else>
      Pythons are not cheaper than elephants today.
    </#if>

This prints ''Pythons are cheaper than elephants today.'' if the price of python is less than the price of elephant, or else it prints ''Pythons are not cheaper than elephants today.''

If you have a variable with boolean value (a true/false thing) then you can use it directly as the `condition` of `if`:

    <#if animals.python.protected>
      Warning! Pythons are protected animals!
    </#if>

###### The list directive

This is useful when you want to list something. For example if you merge this template with the data-model I used earlier to demonstrate sequences:

    <p>We have these animals:
    <table border=1>
      <tr><th>Name<th>Price
      <#list animals as being>
      <tr><td>${being.name}<td>${being.price} Euros
      </#list>
    </table>

then the output will be:

    <p>We have these animals:
    <table border=1>
      <tr><th>Name<th>Price
      <tr><td>mouse<td>50 Euros
      <tr><td>elephant<td>5000 Euros
      <tr><td>python<td>4999 Euros
    </table>

The generic format of the `list` directive is:

`<#list sequence as loopVariable>repeatThis</#list>`

The `repeatThis` part will be repeated for each item in the sequence that you have given with `sequence`, one after the other, starting from the first item. In all repetitions `loopVariable` will hold the value of the current item. This variable exists only between the `<#list ...>` and `</#list>` tags.

As another example, we list the fruits of that example data model:

    <p>And BTW we have these fruits:
    <ul>
    <#list whatnot.fruits as fruit>
     <li>${fruit}
    </#list>
    <ul>

The `whatnot.fruits` expression should be familiar to you; it references a variable in the data-model.

###### The include directive

With the `include` directive you can insert the content of another file into the template.

Suppose you have to show the same copyright notice on several pages. You can create a file that contains the copyright notice only, and insert that file everywhere where you need that copyright notice. Say, you store this copyright notice in `copyright_footer.html`:

    <hr>
    <i>
    Copyright (c) 2000 <a href="http://www.acmee.com">Acmee Inc</a>,
    <br>
    All Rights Reserved.
    </i>

Whenever you need that file you simply insert it with the `include` directive:

    <html>
    <head>
      <title>Test page</title>
    </head>
    <body>
      <h1>Test page</h1>
      <p>Blah blah...
    <#include "/copyright_footer.html">
    </body>
    </html>

and the output will be:

    <html>
    <head>
      <title>Test page</title>
    </head>
    <body>
      <h1>Test page</h1>
      <p>Blah blah...
    <hr>
    <i>
    Copyright (c) 2000 <a href="http://www.acmee.com">Acmee Inc</a>,
    <br>
    All Rights Reserved.
    </i>
    </body>
    </html>

If you change the `copyright_footer.html`, then the visitor will see the new copyright notice on all pages.

##### Using directives together

You can use directives as many times on a page as you want, and you can nest directives into each other similarly as you can nest HTML elements into each other. For example this will list the animals and print the name of large animals with bigger font:

    <p>We have these animals:
    <table border=1>
      <tr><th>Name<th>Price
      <#list animals as being>
      <tr>
        <td>
          <#if being.size == "large"><font size="+1"></#if>
          ${being.name}
          <#if being.size == "large"></font></#if>
        <td>${being.price} Euros
      </#list>
    </table>

Note that since FreeMarker does not interpret text outside FTL tags, interpolations and comments, it doesn't see the above `font` tags as badly nested ones.

##### Dealing with missing variables

In practice the data-model often has variables that are optional (i.e., sometimes missing). To spot some typical human mistakes, FreeMarker doesn't tolerate the referring to missing variables unless you tell them explicitly what to do if the variable is missing. Here we will show the two most typical ways of doing that.

Note for programmers: A non-existent variable and a variable with `null` value is the same for FreeMarker, so the "missing" term used here covers both cases.

Wherever you refer to a variable, you can specify a default value for the case the variable is missing, by following the variable name with a `!` and the default value. Like in the following example, when `user` is missing from data model, the template will behave like if `user`'s value were the string `"Anonymous"`. (When `user` isn't missing, this template behaves exactly like if `!"Anonymous"` were not there):

    <h1>Welcome ${user!"Anonymous"}!</h1>

You can ask whether a variable isn't missing by putting `??` after its name. Combining this with the already introduced `if` directive you can skip the whole greeting if the `user` variable is missing:

    <#if user??><h1>Welcome ${user}!</h1></#if>

Regarding variable accessing with multiple steps, like `animals.python.price`, writing `animals.python.price!0` is correct only if `animals.python` is never missing and only the last subvariable, `price`, is possibly missing (in which case here we assume it's `0`). If `animals` or `python` is missing, the template processing will stop with an "undefined variable" error. To prevent that, you have to write `(animals.python.price)!0`. In that case the expression will be `0` even if `animals` or `python` is missing. Same logic goes for `??`; `animals.python.price??` versus `(animals.python.price)??`.

### Values, Types

#### Basics

It is assumed that you have already read the chapter.

Understanding the concept of values and types is crucial for the understanding of data-models. However, the concept of values and types is not confined to data-models, as you will see.

##### What is a value?

Real programmers can safely skip this section.

Examples of values as you know the term from the everyday math are 16, 0.5, and so on, i.e. numbers. In the case of computer languages the value term has a wider meaning, as a value needn't be a number. For example, take this data-model:

    (root)
     |
     +- user = "Big Joe"
     |
     +- today = Jul 6, 2007
     |
     +- todayHoliday = false
     |
     +- lotteryNumbers
     |   |
     |   +- (1st) = 20
     |   |
     |   +- (2st) = 14
     |   |
     |   +- (3rd) = 42
     |   |
     |   +- (4th) = 8
     |   |
     |   +- (5th) = 15
     |
     +- cargo
         |
         +- name = "coal"
         |
         +- weight = 40

We say that the value of the the `user` variable is "Big Joe" (a string), the value of `today` is Jul 6, 2007 (a date), the value of `todayHoliday` is false (a boolean, ie. a yes/no thing). The value of `lotteryNumbers` is the sequence that contains 20, 14, 42, 8, 15. Surely `lotteryNumbers` is multiple values in the sense that it contains multiple values (for example, the 2nd item in it is a the value 14), but still, `lotteryNumbers` itself is a single value. It's like a box that contains many other items; the whole box can be seen as a single item. Last not least we also have the value of `cargo`, which is a hash (a box-like thing again).So, a value is something that can be stored in a variable (e.g., in `user` or `cargo` or `cargo.name`). But a value need not be stored in a variable to be called a value, for example we have the value 100 here:

    <#if cargo.weight < 100>Light cargo</#if>

The temporaly result of a calculations are also called values, like 20 and 120 when this template is executed (it will print 120):

    ${cargo.weight / 2 + 100}

Explanation for this last: As the result of dividing the two values, 40 (the weight of the cargo) and 2, a new value 20 is created. Then 100 is added to it, so the value 120 is created. Then 120 is printed (`${...}`), and the template execution goes on and all these values gone.

Certainly now you feel what the value term means.

value

##### What is type?

Values have an important aspect, their type. For example the type of the value of the `user` variable is string, and the type of the value of the `lotteryNumbers` variable is sequence. The type of a value is important because it determines to a large extent how and where you can use the value. Like `${user / 2}` is an error, but `${cargo.weight / 2}` works and prints 20, since division only does make sense for a number, but not for a string. Or, using dot like in `cargo.name` does make sense only if `cargo` is a hash. Or, you can list with `<#list ...>` sequences only. Or, the condition of `<#if ...>` must be a boolean. And so on.

A little terminology... Saying "a boolean" or "a boolean value" or "a value of type boolean" are all the same.

A value can have multiple types at the same time, although it's rarely utilized. For example in the data-model below `mouse` is both a string and a hash:

Multi-typed value

    (root)
     |
     +- mouse = "Yerri"
         |
         +- age = 12
         |
         +- color = "brown"

If you merge this template with the above data-model:

    ${mouse}       <#-- uses mouse as a string -->
    ${mouse.age}   <#-- uses mouse as a hash -->
    ${mouse.color} <#-- uses mouse as a hash -->

the output will be:

    Yerri
    12
    brown

##### The data-model is a hash

Looking at the various data-model examples you may already realized: the thing marked as "(root)" is just a value of type hash. When you write something like `user`, that means that you want the "user" variable stored in the root hash. Like if you were writing `root.user`, except that there is no variable called "root" so that wouldn't work.

Some may get confused by the fact that our example data-model, that is, the root hash, contains further hashes and sequences (`lotteryNumbers` and `cargo`). There is nothing special in that. A hash contains other variables, and those variables have a value, which can be a string, a number, etc., and of course it can be a hash or sequence as well. Because, as it was explained earlier, a sequence or a hash is just a value, like a string or a number is.

#### The types

The suppored types are:

- Scalars:

  - String

  - Number

  - Boolean

  - Date

- Containers:

  - Hash

  - Sequence

  - Collection

- Subroutines:

  - Methods and functions

  - User-defined directives

- Miscellaneous/seldom used:

  - Node

##### Scalars

These are the basic, simple kind of values. They can be:

- String: It is simple text, e.g., the name of a product.

  string the FTL value type

  If you want to give a string value directly in the template, rather than use a variable that comes from the data model, you write the text between quotation marks, e.g., `"green mouse"` or `'green mouse'`. (More details regarding the syntax can be found later.)

- Number: For example the price of a product. Whole numbers and non-whole numbers are not distinguished; there is only a single number type. So for example 3/2 will be always 1.5, and never 1. Just like if you are using a calculator.

  number the FTL value type

  If you want to give a numerical value directly in the template, then you write for example: `150` or `-90.05` or `0.001`. (More details regarding the syntax can be found later.)

- Boolean: A boolean value represents a logical true or false (yes or no). For example, if a the visitor has been logged in or not. Typically you use booleans as the condition of the `if` directive, like `<#if loggedIn >...</#if>` or `<#if price == 0>...</#if>`; in the last case the result of the `price == 0` part is a boolean value.

  boolean the FTL value type

  In the templates you can directly specify a boolean with the reserved words `true` and `false`.

- Date: A date variable stores date/time related data. It has three variations:

  date the FTL value type
  time the FTL value type
  date-time the FTL value type

  - A date with day precision (often referred simply as "date") as April 4, 2003

  - Time of day (without the date part), as 10:19:18 PM. Time is stored with millisecond precision.

  - Date-time (sometimes called "time stamp") as April 4, 2003 10:19:18 PM. The time part is stored with millisecond precision.

  Unfortunately, because of the limitations of the Java platform, FreeMarker sometimes can't decide which parts of the date are in use (i.e., if it is date-time, or a time of day, etc.). The solution for this problem is an advanced topic that will be discussed later.

  It is possible to define date values directly in templates, but this is an advanced topic that will be explained later.

Bear in mind that FreeMarker distinguishes strings from numbers and booleans, so the string `"150"` and the number `150` are totally different. A number holds a numerical value. A boolean holds a logical true or false. A string holds an arbitrary sequence of characters.

##### Containers

Re-explanation of hashes and sequences from a more ''professional'' viewpoint as earlier, and some meditation about them.

These are the values whose purpose is to contain other variables; they are just containers. The contained variables are often referred as subvariables. The container types are:

- Hash: Associates a unique lookup name with each of its subvariables. The name is an unrestricted string. A hash doesn't define an ordering for the subvariables in it. That is, there is no such thing as the first subvariable, and the second subvariable, etc.; the variables are just accessed by name.

  hash the FTL value type

- Sequence: Associates an integer number with each of its subvariables. The first subvariable is associated with 0, the second with 1, the third to 2, and so on; the subvariables are ordered. These numbers are often called the indexes of the subvariables. Sequences are usually dense, i.e., all indexes up to the index of the last subvariable have an associated subvariable, but it's not strictly necessary. The type of the subvariable values need not be the same.

  sequence the FTL value type

- Collection: A collection, from the viewpoint of the template author, is a restricted sequence. You cannot access its size or retrieve its subvariables by index, but they can be still listed with the `list` directive.

  collection the FTL value type

Note that since a value can have multiple types, it is possible for a value to be both a hash and a sequence, in which case it would support index-based access as well as access by lookup name. However, typically a container will be either a hash or a sequence, not both.

As the value of the variables stored in hashes and sequences (and collections) can be anything, it can be a hash or sequence (or collection) as well. This way you can build arbitrarily deep structures.

The data-model itself (or better said the root of it) is a hash.

##### Subroutines

###### Methods and functions

A value that is a method or a function is used to calculate another value, influenced by the parameters you give to it.

For programmer types: Methods/functions are first-class values, just like in functional programming languages. This means that functions/methods can be the parameters or return values of other functions/methods, you can assign them to variables, and so on.

Suppose that programmers have put the method variable `avg` in the data-model that can be used to calculate the average of numbers. If you give the 3 and 5 as parameters when you access `avg`, then you get the value 4.

The usage of methods will be explained later, but perhaps this example helps to understand what methods are:

    The average of 3 and 5 is: ${avg(3, 5)}
    The average of 6 and 10 and 20 is: ${avg(6, 10, 20)}
    The average of the price of a python and an elephant is:
    ${avg(animals.python.price, animals.elephant.price)}

this will output:

    The average of 3 and 5 is: 4
    The average of 6 and 10 and 20 is: 12
    The average of the price of a python and an elephant is:
    4999.5

What is the difference between a method and a function? As far as the template author is concerned, nothing. Well not really nothing, as methods typically come from the data-model (as they reflect the methods of Java objects), and functions are defined in templates (with the `function` directive -- an advanced topic), but both can be used on the same way.

method the FTL value type

###### User-defined directives

A value of this type can be used as user-defined directive (with other words, as FreeMarker tag). An user-defined directive is a subroutine, something like a little reusable template fragment. But this is an advanced topic that will be explained later in its own chapter.

For programmer types: user-defined directives (such as macros), are first-class values too, just like functions/methods are.

Just to get an idea about user-defined directives (so just ignore this if you won't understand), assume we have a variable, `box`, whose value is a user-defined directive that prints some kind of fancy HTML message box with a title bar and a message in it. The `box` variable could be used in the template like this (for example):

    <@box title="Attention!">
      Too much copy-pasting may leads to
      maintenance headaches.
    </@box>

macro the FTL value type
directive the FTL value type
user-defined directive the FTL value type

###### Function/method versus user-defined directive

This is for advanced users again (so ignore it if you don't understand). It's a frequent dilemma if you should use a function/method or an user-defined directive to implement something. The rule of thumb is: Implement the facility as user-defined directive instead of as function/method if:

- ... the output (the return value) is markup (HTML, XML, etc.). The main reason is that the result of functions are subject to automatic XML-escaping (due to the nature of `${...}`), while the output of user-defined directives are not (due to the nature of `<@...>`; its output is assumed to be markup, and hence already escaped).

- ... it's the side-effect that is important and not the return value. For example, a directive whose purpose is to add an entry to the server log is like that. (In fact you can't have a return value for a user-defined directive, but some kind of feedback is still possible by setting non-local variables.)

- ... it will do flow control (like for example `list` or `if` directives do). You just can't do that with a function/method anyway.

The Java methods of FreeMarker-unaware Java objects are normally visible as methods in templates, regardless of the nature of the Java method. That said, you have no choice there.

##### Miscellaneous

###### Nodes

Node variables represent a node in a tree structure, and are used mostly with XML processing, which is an advanced, and specialized topic.

Still, a quick overview for advanced users: A node is similar to a sequence that stores other nodes, which are often referred as the children nodes. A node stores a reference to its container node, which is often referred as the parent node. The main point of being a node is the topological information; other data must be stored by utilizing that a value can have multiple types. Like, a value may be both a node and a number, in which case it can store a number as the "pay-load". Apart from the topological information, a node can store some metainformation as well: a node name, a node type (string), and a node namespace (string). For example, if the node symbolizes a `h1` element in an XHTML document, then its name could be `"h1"`, it's node type could be `"element"`, and it's namespace could be `"http://www.w3.org/1999/xhtml"`. But it's up to the designer of the data-model if what meaning these metainformations have, and if they are used at all. The way of retrieving the topological and metainformations is described in a later chapter (that you don't have to understand at this point).

node the FTL value type

### The Template

It is assumed that you have already read the and the chapter.

#### Overall structure

Templates are in fact programs you write in a language called FTL (for FreeMarker Template Language). This is a quite simple programming language designed for writing templates and nothing else.

FTL

A template (= FTL program) is a mix of the following sections:

- Text: Text that will be printed to the output as is.

  text

- Interpolation: These sections will be replaced with a calculated value in the output. Interpolations are delimited by `${` and `}` (or with `#{` and `}`, but that shouldn't be used anymore; see more here).

  interpolation

- FTL tags: FTL tags are a bit similar to HTML tags, but they are instructions to FreeMarker and will not be printed to the output.

  FTL tag

- Comments: Comments are similar to HTML comments, but they are delimited by `<#--` and `-->`. Comments will be ignored by FreeMarker, and will not be written to the output.

  comment
  <#--...-->
  #

Let's see a concrete template. I have marked the template's components with colors: text, interpolation, FTL tag, comment. With the [BR]-s I intend to visualize the line breaks.

    <html>[BR]
    <head>[BR]
      <title>Welcome!</title>[BR]
    </head>[BR]
    <body>[BR]
      <#-- Greet the user with his/her name -->[BR]
      <h1>Welcome ${user}!</h1>[BR]
      <p>We have these animals:[BR]
      <ul>[BR]
      <#list animals as being>[BR]
        <li>${being.name} for ${being.price} Euros[BR]
      </#list>[BR]
      </ul>[BR]
    </body>[BR]
    </html>

FTL distinguishes upper case and lower case letters. So `list` is good directive name, while `List` is not. Similarly `${name}` is not the same as `${Name}` or `${NAME}`

It is important to realize that interpolations can be used in text (and in string literal expressions; see later) only.

An FTL tag can't be inside another FTL tag nor inside an interpolation. For example this is WRONG: `<#if <#include 'foo'>='bar'>...</#if>`

Comments can be placed inside FTL tags and interpolations. For example:

    <h1>Welcome ${user <#-- The name of user -->}!</h1>[BR]
    <p>We have these animals:[BR]
    <ul>[BR]
    <#list <#-- some comment... --> animals as <#-- again... --> being>[BR]
    ...

For those of you who have tried the above examples: You may notice that some of spaces, tabs and line breaks are missing from the template output, even though we said that text is printed as is. Don't bother with it now. This is because the feature called ''white-space stripping'' is turned on, and that automatically removes some superfluous spaces, tabs and line breaks. This will be explained later.

#### Directives

Note that the Expressions chapter depends on this chapter, and Interpolations chapter depends on Expressions chapter. Thus Directives must be the first chapter after Basics.

You use FTL tags to call directives. In the example you have called the `list` directive. Syntactically you have done it with two tags: `<#list animals as being>` and `</#list>`.

directive

There are two kind of FTL tags:

FTL tag

- Start-tag: `<#directivename parameters>`

- End-tag: `</#directivename>`

This is similar to HTML or XML syntax, except that the tag name starts with `#`. If the directive doesn't have nested content (content between the start-tag and the end-tag), you must use the start-tag with no end-tag. For example you write `<#if something>...</#if>`, but just `<#include something>` as FreeMarker knows that the `include` directive can't have nested content.

The format of the `parameters` depends on the `directivename`.

In fact there are two types of directives: predefined directives and user-defined directives. For user-defined directives you use `@` instead of `#`, for example `<@mydirective parameters>...</@mydirective>`. Further difference is that if the directive has no nested content, you must use a tag like `<@mydirective parameters />`, similarly as in XML (e.g. `<img ... />`). But user-defined directives is an advanced topic that will be discussed later.

FTL tags, like HTML tags, must be properly nested. So the code below is wrong, as the `if` directive is both inside and outside of the nested content of the `list` directive:

    <ul>
    <#list animals as being>
      <li>${being.name} for ${being.price} Euros
      <#if user == "Big Joe">
         (except for you)
    </#list> <#-- WRONG! The "if" has to be closed first. -->
    </#if>
    </ul>

Note that FreeMarker doesn't care about the nesting of HTML tags, only about the nesting of FTL tags. It just sees HTML as flat text, it doesn't interpret it in any way.

If you try to use a non-existing directive (e.g., you mistype the directive name), FreeMarker will decline to use the template and produce an error message.

FreeMarker ignores superfluous white-space inside FTL tags. So you can write this:

    <#list[BR]
      animals       as[BR]
         being[BR]
    >[BR]
    ${being.name} for ${being.price} Euros[BR]
    </#list    >

You may not, however, insert white-space between the `<` or `</` and the directive name.

The complete list and description of all directives can be found in the (but I recommend that you look at the chapter about expressions first).

FreeMarker can be configured to use `[` and `]` instead of `<` and `>` in the FTL tags and FTL comments, like `[#if user == "Big Joe"]...[/#if]`. For more information read: .

FreeMarker can be configured so that it understands predefined directives without `#` (like `<if user == "Big Joe">...</if>`). However we don't recommend the usage of this mode. For more information read:

<#...>
#

#### Expressions

When you supply values for interpolations or directive parameters you can use variables or more complex expressions. For example, if x is the number 8 and y is 5, the value of `(x + y)/2` resolves to the numerical value 6.5.

expression

Before we go into details, let's see some concrete examples:

- When you supply value for interpolations: The usage of interpolations is `${expression}` where expression gives the value you want to insert into the output as text. So `${(5 + 8)/2}` prints ``6.5'' to the output (or possibly ``6,5'' if the language of your output is not US English).

- When you supply a value for the directive parameter: You have already seen the `if` directive in the Getting Started section. The syntax of this directive is: `<#if expression>...</#if>`. The expression here must evaluate to a boolean value. For example in `<#if 2 < 3>` the `2 < 3` (2 is less than 3) is an expression which evaluates to `true`.

##### Quick overview (cheat sheet)

This is a reminder for those of you who already know FreeMarker or are just experienced programmers:

- Specify values directly

  - Strings: `"Foo"` or `'Foo'` or `"It's \"quoted\""` or `r"C:\raw\string"`

  - Numbers: `123.45`

  - Booleans: `true`, `false`

  - Sequences: `["foo", "bar", 123.45]`, `1..100`

  - Hashes: `{"name":"green mouse", "price":150}`

- Retrieving variables

  - Top-level variables: `user`

  - Retrieving data from a hash: `user.name`, `user["name"]`

  - Retrieving data from a sequence: `products[5]`

  - Special variable: `.main`

- String operations

  - Interpolation (or concatenation): `"Hello ${user}!"` (or `"Free" + "Marker"`)

  - Getting a character: `name[0]`

- Sequence operations

  - Concatenation: `users + ["guest"]`

  - Sequence slice: `products[10..19]` or `products[5..]`

- Hash operations

  - Concatenation: `passwords + {"joe":"secret42"}`

- Arithmetical calculations: `(x * 1.5 + 10) / 2 - y % 100`

- Comparison: `x == y`, `x != y`, `x < y`, `x > y`, `x >= y`, `x <= y`, `x &lt; y`, ...etc.

- Logical operations: `!registered && (firstVisit || fromEurope)`

- Built-ins: `name?upper_case`

- Method call: `repeat("What", 3)`

- Missing value handler operators:

  - Default value: `name!"unknown"` or `(user.name)!"unknown"` or `name!` or `(user.name)!`

  - Missing value test: `name??` or `(user.name)??`

See also: Operator precedence

##### Specify values directly

Often you want to specify a value directly and not as a result of some calculations.

###### Strings

To specify a string value directly you give the text in quotation marks, e.g.: `"some text"` or in apostrophe-quote, e.g. `'some text'`. The two forms are equivalent. If the text itself contains the character used for the quoting (either `"` or `'`) or backslashes, you have to precede them with a backslash; this is called escaping. You can type any other character, including line breaks, in the text directly. Example:

    ${"It's \"quoted\" and
    this is a backslash: \\"}

    ${'It\'s "quoted" and
    this is a backslash: \\'}

will print:

    It's "quoted" and
    this is a backslash: \

    It's "quoted" and
    this is a backslash: \

Of course, you could simply type the above text into the template, without using `${...}`. But we do it here just for the sake of example, to demonstrate expressions.

This is the list of all supported escape sequences. All other usage of backlash in string literals is an error and any attempt to use the template will fail.

Escape sequence | Meaning
--- | ---
`\"` | Quotation mark (u0022)
`\'` | Apostrophe (a.k.a. apostrophe-quote) (u0027)
`\\` | Back slash (u005C)
`\n` | Line feed (u000A)
`\r` | Carriage return (u000D)
`\t` | Horizontal tabulation (a.k.a. tab) (u0009)
`\b` | Backspace (u0008)
`\f` | Form feed (u000C)
`\l` | Less-than sign: `<`
`\g` | Greater-than sign: `>`
`\a` | Ampersand: `&`
`\xCode` | Character given with its hexadecimal Unicode code (UCS code)

The `Code` after the `\x` is 1 to 4 hexadecimal digits. For example this all put a copyright sign into the string: `"\xA9 1999-2001"`, `"\x0A9 1999-2001"`, `"\x00A9 1999-2001"`. When the character directly after the last hexadecimal digit can be interpreted as hexadecimal digit, you must use all 4 digits or else FreeMarker will be confused.

Note that the character sequence `${` (and `#{`) has special meaning. It's used to insert the value of expressions (typically: the value of variables, as in `"Hello ${user}!"`). This will be explained later. If you want to print `${`, you should use raw string literals as explained below.

A special kind of string literals is the raw string literals. In raw string literals, backslash and `${` have no special meaning, they are considered as plain characters. To indicate that a string literal is a raw string literal, you have to put an `r` directly before the opening quotation mark or apostrophe-quote. Example:

    ${r"${foo}"}
    ${r"C:\foo\bar"}

will print:

    ${foo}
    C:\foo\bar

string literal
escape sequences
raw string literal

###### Numbers

To specify a numerical value directly you type the number without quotation marks. You have to use the dot as your decimal separator and must not use any grouping separator symbols. You can use `-` or `+` to indicate the sign (`+` is redundant). Scientific notation is not yet supported (so `1E3` is wrong). Also, you cannot omit the 0 before the decimal separator (so `.5` is wrong).

Examples of valid number literals: `0.08`, `-5.013`, `8`, `008`, `11`, `+11`

Note that numerical literals like `08`, `+8`, `8.00` and `8` are totally equivalent as they all symbolize the number eight. Thus, `${08}`, `${+8}`, `${8.00}` and `${8}` will all print exactly same.

number literal

###### Booleans

To specify a boolean value you write `true` or `false`. Don't use quotation marks.

boolean literal
literal boolean

###### Sequences

To specify a literal sequence, you list the subvariables separated by commas, and put the whole list into square brackets. For example:

    <#list ["winter", "spring", "summer", "autumn"] as x>
    ${x}
    </#list>

will print:

    winter
    spring
    summer
    autumn

The items in the list are expressions, so you can do this for example: `[2 + 2, [1, 2, 3, 4], "whatnot"]`. Here the first subvariable will be the number 4, the second will be another sequence, and the third subvariable will be the string "whatnot".

You can define sequences that store a numerical range with `start..end`, where `start` and `end` are expressions that resolve to numerical values. For example `2..5` is the same as `[2, 3, 4, 5]`, but the former is much more efficient (occupies less memory and faster). Note that the square brackets are missing. You can define decreasing numerical ranges too, e.g.: `5..2`. (Furthermore, you can omit the `end`, for example `5..`, in which case the sequence will contain 5, 6, 7, 8, ...etc up to the infinity.)

sequence literal
numerical sequence
numerical range expression
range expression

###### Hashes

To specify a hash in a template, you list the key/value pairs separated by commas, and put the list into curly brackets. The key and value within a key/value pair are separated with a colon. Here is an example: `{"name":"green mouse", "price":150}`. Note that both the names and the values are expressions. However, the lookup names must be strings.

hash literal
literal hash
literal
constant

##### Retrieving variables

###### Top-level variables

To access a top-level variable, you simply use the variable name. For example, the expression `user` will evaluate to the value of variable stored with name ``user'' in the root. So this will print what you store there:

    ${user}

If there is no such top-level variable, then an error will result when FreeMarker tries to evaluate the expression, and it aborts template processing (unless programmers has configured FreeMarker differently).

In this expression the variable name can contain only letters (including non-Latin letters), digits (including non-Latin digits), underline (_), dollar ($), at sign (@) and hash (#). Furthermore, the name must not start with digit.

subvariable accessing

###### Retrieving data from a hash

If we already have a hash as a result of an expression, then we can get its subvariable with a dot and the name of the subvariable. Assume that we have this data-model:

    (root)
     |
     +- book
     |   |
     |   +- title = "Breeding green mouses"
     |   |
     |   +- author
     |       |
     |       +- name = "Julia Smith"
     |       |
     |       +- info = "Biologist, 1923-1985, Canada"
     |
     +- test = "title"

Now we can read the `title` with `book.title`, since the book expression will return a hash (as explained in the last chapter). Applying this logic further, we can read the name of the author with this expression: `book.author.name`.

There is an alternative syntax if we want to specify the subvariable name with an expression: `book["title"]`. In the square brackets you can give any expression as long as it evaluates to a string. So with this data-model you can also read the title with `book[test]`. More examples; these are all equivalent: `book.author.name`, `book["author"].name`, `book.author.["name"]`, `book["author"]["name"]`.

When you use the dot syntax, the same restrictions apply regarding the variable name as with top-level variables (name can contain only letters, digits, _, $, @, etc.). There are no such restrictions when you use the square bracket syntax, since the name is the result of an arbitrary expression. (Note, that to help the FreeMarker XML support, if the subvariable name is `*` (asterisk) or `**`, then you do not have to use square bracket syntax.)

As with the top-level variables, trying to access a non-existent subvariable causes an error and aborts the processing of the template (unless programmers has configured FreeMarker differently).

subvariable accessing
hash accessing subvariable

###### Retrieving data from a sequence

This is the same as for hashes, but you can use the square bracket syntax only, and the expression in the brackets must evaluate to a number, not a string. For example to get the name of the first animal of the example data-model (remember that the number of the first item is 0, not 1): `animals[0].name`

subvariable accessing
sequence accessing subvariable

###### Special variables

Special variables are variables defined by the FreeMarker engine itself. To access them, you use the `.variable_name` syntax.

Normally you don't need to use special variables. They are for expert users. The complete list of special variables can be found in the reference.

special variables

##### String operations

###### Interpolation (or concatenation)

If you want to insert the value of an expression into a string, you can use `${...}` (and `#{...}`) in string literals. `${...}` behaves similarly as in text sections. For example (assume that user is ``Big Joe''):

    ${"Hello ${user}!"}
    ${"${user}${user}${user}${user}"}

will print:

    Hello Big Joe!
    Big JoeBig JoeBig JoeBig Joe

Alternatively, you can use the `+` operator to achieve similar result. This is the old method, and it is called string concatenation. Example:

    ${"Hello " + user + "!"}
    ${user + user + user + user}

This will print the same as the example with the `${...}`-s.

A frequent mistake of users is the usage of interpolations in places where it shouldn't/can't be used. Interpolations work only in text sections (e.g. `<h1>Hello ${name}!</h1>`) and in string literals (e.g. `<#include "/footer/${company}.html">`). A typical bad usage is `<#if ${isBig}>Wow!</#if>`, which is syntactically WRONG. You should simply write `<#if isBig>Wow!</#if>`. Also, `<#if "${isBig}">Wow!</#if>` is WRONG too, since the parameter value will be a string, and the `if` directive wants a boolean value, so it will cause a runtime error.

interpolation
concatenate strings
joining strings
string concatenate
string interpolation
adding strings

###### Getting a character

You can get a single character of a string at a given index similarly as you can read the subvariable of a sequence, e.g. `user[0]`. The result will be a string whose length is 1; FTL doesn't have a separate character type. As with sequence subvariables, the index must be a number that is at least 0 and less than the length of the string, or else an error will abort the template processing.

Since the sequence subvariable syntax and the character getter syntax clashes, you can use the character getter syntax only if the variable is not a sequence as well (which is possible because FTL supports multi-typed values), since in that case the sequence behavior prevails. (To work this around, you can use the `string` built-in, e.g. `user?string[0]`. Don't worry if you don't understand this yet; built-ins will be discussed later.)

Example (assume that user is ``Big Joe''):

    ${user[0]}
    ${user[4]}

will print (note that the index of the first character is 0):

    B
    J

You can get a range of characters in the same way as you get a sequence slice, e.g `${user[1..4]}` and `${user[4..]}`. However, it's now depreacted to utilize this, and instead you should use the `substring` built-in; built-ins will be discussed later.

charAt
get character
string operations

##### Sequence operations

###### Concatenation

You can concatenate sequences in the same way as strings, with `+`. Example:

    <#list ["Joe", "Fred"] + ["Julia", "Kate"] as user>
    - ${user}
    </#list>

will print:

    - Joe
    - Fred
    - Julia
    - Kate

Note that sequence concatenation is not to be used for many repeated concatenations, like for appending items to a sequence inside a loop. It's just for things like `<#list users + admins as person>`. Although concatenating sequences is fast and its speed is independently of the size of the concatenated sequences, the resulting sequence will be always a little bit slower to read than the original two sequences were. This way the result of many repeated concatenations is a sequence that is slow to read.

concatenate sequences
joining sequences
sequence concatenate
adding sequences

###### Sequence slice

With `[firstindex..lastindex]` you can get a slice of a sequence, where `firstindex` and `lastindex` are expressions evaluate to number. For example, if `seq` stores the sequence `"a"`, `"b"`, `"c"`, `"d"`, `"e"`, `"f"` then the expression `seq[1..4]` will evaluate to a sequence that contains `"b"`, `"c"`, `"d"`, `"e"` (since the item at index 1 is `"b"`, and the item at index 4 is `"e"`).

The `lastindex` can be omitted, in which case it defaults to the index of the last item of the sequence. For example, if `seq` stores the sequence `"a"`, `"b"`, `"c"`, `"d"`, `"e"`, `"f"` again, then `seq[3..]` will evaluate to a sequence that contains `"d"`, `"e"`, `"f"`.

`lastindex` can be omitted only since FreeMarker 2.3.3.

An attempt to access a subvariable past the last subvariable or before the first subvariable of the sequence will cause an error and abort the processing of the template.

sequence slice
sequence slice
subsequence
sequence operations

##### Hash operations

###### Concatenation

You can concatenate hashes in the same way as strings, with `+`. If both hashes contain the same key, the hash on the right-hand side of the `+` takes precedence. Example:

    <#assign ages = {"Joe":23, "Fred":25} + {"Joe":30, "Julia":18}>
    - Joe is ${ages.Joe}
    - Fred is ${ages.Fred}
    - Julia is ${ages.Julia}

will print:

    - Joe is 30
    - Fred is 25
    - Julia is 18

Note that hash concatenation is not to be used for many repeated concatenations, like for adding items to a hash inside a loop. It's the same as with the sequence concatenation.

concatenate hashes
joining hashes
hash concatenate
adding hashes
hash operations

##### Arithmetical calculations

This is the basic 4-function calculator arithmetic plus the modulus operator. So the operators are:

- Addition: `+`

- Subtraction: `-`

- Multiplication: `*`

- Division: `/`

- Modulus (remainder): `%`

Information about the precision?

Example:

    ${100 - x * x}
    ${x / 2}
    ${12 % 10}

Assuming that `x` is 5, it will print:

    75
    2.5
    2

Both operands must be expressions which evaluate to a numerical value. So the example below will cause an error when FreeMarker tries to evaluate it, since `"5"` is a string and not the number 5:

    ${3 * "5"} <#-- WRONG! -->

There is an exception to the above rule. The `+` operator, is used to concatenate strings as well. If on one side of `+` is a string and on the other side of `+` is a numerical value, then it will convert the numerical value to string (using the format appropriate for language of the page) and then use the `+` as string concatenation operator. Example:

    ${3 + "5"}

will output this:

    35

Generally, FreeMarker never converts a string to a number automatically, but it may convert a number to a string automatically.

People often want only the integer part of the result of a division (or of other calculations). This is possible with the `int` built-in. (Built-ins are explained later):

integer division
integer part

    ${(x/2)?int}
    ${1.1?int}
    ${1.999?int}
    ${-1.1?int}
    ${-1.999?int}

Assuming that `x` is 5, it will print:

    2
    1
    1
    -1
    -1

arithmetic
math
addition
subtraction
division
modulus

##### Comparison

Sometimes you want to know if two values are equal or not, or which value is the greater.

To show concrete examples I will use the `if` directive here. The usage of `if` directive is: `<#if expression>...</#if>`, where expression must evaluate to a boolean value or else an error will abort the processing of the template. If the value of expression is `true` then the things between the begin and end-tag will be processed, otherwise they will be skipped.

To test two values for equality you use `=` (or `==` as in Java or C; the two are absolutely equivalent.) To test two values for inequality you use `!=`. For example, assume that `user` is ``Big Joe'':

    <#if user = "Big Joe">
      It is Big Joe
    </#if>
    <#if user != "Big Joe">
      It is not Big Joe
    </#if>

The `user = "Big Joe"` expression in the `<#if ...>` will evaluate to the boolean `true`, so the above will say ``It is Big Joe''.

The expressions on both sides of the `=` or `!=` must evaluate to a scalar. Furthermore, the two scalars must have the same type (i.e. strings can only be compared to strings and numbers can only be compared to numbers, etc.) or else an error will abort template processing. For example `<#if 1 = "1">` will cause an error. Note that FreeMarker does exact comparison, so string comparisons are case and white-space sensitive: `"x"` and `"x "` and `"X"` are not equal values.

For numerical and date values you can also use `<`, `<=`, `>=` and `>`. You can't use them for strings! Example:

    <#if x <= 12>
      x is less or equivalent with 12
    </#if>

There is a little problem with `>=` and `>`. FreeMarker interprets the `>` as the closing character of the FTL tag. To prevent this, you have to put the expression into parentheses: `<#if (x > y)>`. Or, you can use `&gt;` and `&lt;` on the place of the problematic relation marks: `<#if x &gt; y>`. (Note that in general FTL does not support entity references (those `&...;` things) in FTL tags; it is just an exception with the arithmetical comparisons.). Also, as an alternative you can use `lt` instead of `<`, `lte` instead of `<=`, `gt` instead of `>` and `gte` instead of `>=`. And, for historical reasons FTL also understands `\lt`, `\lte`, `\gt` and `\gte` which are the same as the ones without the backslash.

comparison operators

##### Logical operations

Just the usual logical operators:

- Logical or: `||`

- Logical and: `&&`

- Logical not: `!`

The operators will work with boolean values only. Otherwise an error will abort the template processing.

Example:

    <#if x < 12 && color = "green">
      We have less than 12 things, and they are green.
    </#if>
    <#if !hot> <#-- here hot must be a boolean -->
      It's not hot.
    </#if>

boolean operations
logical operations
or
and
not

##### Built-ins

Built-ins provide, as the name suggest, certain built-in functionality that is always available. Typically, a built-in provides a different version of a variable, or some information about the variable in question. The syntax for accessing a built-in is like that of accessing a subvariable in a hash, except that you use the question mark instead of a dot. For example, to get the upper case version of a string: `user?upper_case`.

You can find the complete list of built-ins in the Reference. For now, just a few of the more important ones:

- Built-ins to use with strings:

  - `html`: The string with all special HTML characters replaced with entity references (E.g. `<` with `&lt;`).

  - `cap_first`: The string with the first letter converted to upper case

  - `lower_case`: The lowercase version of the string

  - `upper_case`: The uppercase version of the string

  - `trim`: The string without leading and trailing white-spaces

- Built-ins to use with sequences:

  - `size`: The number of elements in the sequence

- Built-ins to use with numbers:

  - `int`: The integer part of a number (e.g. `-1.9?int` is `-1`)

Example:

    ${test?html}
    ${test?upper_case?html}

Assuming that `test` stores the string ``Tom & Jerry'', the output will be:

    Tom &amp; Jerry
    TOM &amp; JERRY

Note the `test?upper_case?html`. Since the result of `test?upper_case` is a string, you can use the `html` built-in with it.

Another example:

    ${seasons?size}
    ${seasons[1]?cap_first} <#-- left side can by any expression -->
    ${"horse"?cap_first}

Assuming that `seasons` stores the sequence `"winter"`, `"spring"`, `"summer"`, `"autumn"`, the output will be:

    4
    Spring
    Horse

built-in

##### Method call

If you have a method then you can use the method call operation on it. The method call operation is a comma-separated list of expressions in parentheses. These values are called parameters. The method call operation passes these values to the method which will in turn return a result. This result will be the value of the whole method call expression.

For example, assume the programmers have made available a method variable called `repeat`. You give a string as the first parameter, and a number as the second parameter, and it returns a string which repeats the first parameter the number of times specified by the second parameter.

    ${repeat("What", 3)}

will print:

    WhatWhatWhat

Here `repeat` was evaluated to the method variable (according to how you access top-level variables) and then `("What", 3)` invoked that method.

I would like to emphasize that method calls are just plain expressions, like everything else. So this:

    ${repeat(repeat("x", 2), 3) + repeat("What", 4)?upper_case}

will print this:

    xxxxxxWHATWHATWHATWHAT

call a method
method call

##### Handling missing values

These operators exist since FreeMarker 2.3.7 (replacing the `default`, `exists` and `if_exists` built-ins).

As we explained earlier, an error will occur and abort the template processing if you try to access a missing variable. However two special operators can suppress this error, and handle the problematic situation. The handled variable can be top-level variable, hash subvariable, or sequence subvariable as well. Furthermore these operators handle the situation when a method call doesn't return a value (from the viewpoint of Java programmers: it returns `null` or it's return type is `void`), so it's more correct to say that these operators handle missing values in general, rather than just missing variables.

For those who know what's Java `null`, FreeMarker 2.3.x treats them as missing values. Simply, the template language doesn't know the concept of `null`. For example, if you have a bean that has a `maidenName` property, and the value of that property is `null`, then that's the same as if there were no such property at all, as far as the template is concerned (assuming you didn't configured FreeMarker to use some extreme object wrapper, that is). The result of a method call that returns `null` is also treated as a missing variable (again, assuming that you use some usual object wrapper). See more in the FAQ.

If you wonder why is FreeMarker so picky about missing variables, read this FAQ entry.

###### Default value operator

Synopsis: `unsafe_expr!default_expr` or `unsafe_expr!` or `(unsafe_expr)!default_expr` or `(unsafe_expr)!`

This operator allows you to specify a default value for the case when the value is missing.

Example. Assume no variable called `mouse` is present:

    ${mouse!"No mouse."}
    <#assign mouse="Jerry">
    ${mouse!"No mouse."}

The output will be:

    No mouse.
    Jerry

The default value can be any kind of expression, so it doesn't have to be a string. For example you can write `hits!0` or `colors!["red", "green", "blue"]`. There is no restriction regarding the complexity of the expression that specifies the default value, for example you can write: `cargo.weight!(item.weight * itemCount + 10)`.

If you have a composite expression after the `!`, like `1 + x`, always use parenthesses, like `${x!(1 + y)}` or `${(x!1) + y)}`, depending on which interpretation you meant. That's needed because due to a programming mistake in FreeMarker 2.3.x, the precedence of `!` (when it's used as default value operator) is very low at its right side. This means that, for example, `${x!1 + y}` is misinterpreted by FreeMarker as `${x!(1 + y)}` while it should mean `${(x!1) + y}`. This programming error will be fixed in FreeMarker 2.4, so you should not utilize this wrong behavior, or else your templates will break with FreeMarker 2.4!

If the default value is omitted, then it will be empty string and empty sequence and empty hash at the same time. (This is possible because FreeMarker allows multi-type values.) Note the consequence that you can't omit the default value if you want it to be `0` or `false`. Example:

    (${mouse!})
    <#assign mouse = "Jerry">
    (${mouse!})

The output will be:

    ()
    (Jerry)

Due to syntactical ambiguities `<@something a=x! b=y />` will be interpreted as `<@something a=x!(b=y) />`, that is, the `b=y` will be interpreted as a comparison that gives the default value for `x`, rather than the specification of the `b` parameter. To prevent this, write: `<@something a=(x!) b=y />`

You can use this operator in two ways with non-top-level variables:

    product.color!"red"

This will handle if `color` is missing inside `product` (and returns `"red"` if so), but will not handle if `product` is missing. That is, the `product` variable itself must exist, otherwise the template processing will die with error.

    (product.color)!"red"

This will handle if `product.color` is missing. That is, if `product` is missing, or `product` exists but it does not contain `color`, the result will be `"red"`, and no error will occur. The important difference between this and the previous example is that when surrounded with parentheses, it is allowed for any component of the expression to be undefined, while without parentheses only the last component of the expression is allowed to be undefined.

Of course, the default value operator can be used with sequence subvariables as well:

    <#assign seq = ['a', 'b']>
    ${seq[0]!'-'}
    ${seq[1]!'-'}
    ${seq[2]!'-'}
    ${seq[3]!'-'}

the outpur will be:

    a
    b
    -
    -

A negative sequence index (as `seq[-1]!'-'`) will always cause an error, you can't suppress that with this or any other operator.

default value operator

###### Missing value test operator

Synopsis: `unsafe_expr??` or `(unsafe_expr)??`

This operator tells if a value is missing or not. Depending on that, the result is either `true` or `false`.

Example. Assume no variable called `mouse` is present:

    <#if mouse??>
      Mouse found
    <#else>
      No mouse found
    </#if>
    Creating mouse...
    <#assign mouse = "Jerry">
    <#if mouse??>
      Mouse found
    <#else>
      No mouse found
    </#if>

The output will be:

      No mouse found
    Creating mouse...
      Mouse found

With non-top-level variables the rules are the same as with the default value operator, that is, you can write `product.color??` and `(product.color)??`.

existence test operator
missing value test operator
testing for null
testing for missing
testing for undefined
is null
undefined variable
missing variable
null
handling null-s
error handling

##### Parentheses

Parentheses can be used to group any expressions. Some examples:

                                       <#-- Output will be: -->
    ${3 * 2 + 2}                       <#-- 8 -->
    ${3 * (2 + 2)}                     <#-- 12 -->
    ${3 * ((2 + 2) * (1 / 2))}         <#-- 6 -->
    ${"green " + "mouse"?upper_case}   <#-- green MOUSE -->
    ${("green " + "mouse")?upper_case} <#-- GREEN MOUSE -->
    <#if !( color = "red" || color = "green")>
      The color is nor red nor green
    </#if>

Note that the parentheses of a method call expressions have nothing to do with the parentheses used for grouping.

parentheses

##### White-space in expressions

FTL ignores superfluous white-space in expressions. So these are totally equivalent:

    ${x + ":" + book.title?upper_case}

and

    ${x+":"+book.title?upper_case}

and

    ${
       x
     + ":"   +  book   .   title
       ?   upper_case
          }

##### Operator precedence

The following table shows the precedence assigned to the operators. The operators in this table are listed in precedence order: the higher in the table an operator appears, the higher its precedence. Operators with higher precedence are evaluated before operators with a relatively lower precedence. Operators on the same line have equal precedence. When binary operators (operators with two ``parameters'', as `+` and `-`) of equal precedence appear next to each other, they are evaluated in left-to-right order.

Operator group | Operators
--- | ---
highest precedence operators | `[subvarName] [subStringRange] . ? (methodParams) expr! expr??`
unary prefix operators | `+expr -expr !expr`
multiplicative | `* / %`
additive | `+ -`
relational | `< > <= >=` (and quivalents: `gt`, `lt`, etc.)
equality | `== !=` (and equivalents: `=`)
logical AND | `&&`
logical OR | `||`
numerical range | `..`

For those of you who master C, Java language or JavaScript, note that the precedence rules are the same as in those languages, except that FTL has some operators that do not exist in those languages.

The default value operator (`exp!exp`) is not yet in the table because of a programming mistake, which will be only fixed in FreeMarker 2.4 due to backward compatibility constraints. It meant to be a "highest precedence operator", but in FreeMarker 2.3.x the precedence on its right side is very low by accident. So if you have a composite expression on the right side, always use paranthesses, etiher like `x!(y + 1)` or like `(x!y) + 1`. Never write just `x!y + 1`.

precedence
operator precedence

#### Interpolations

The format of interpolations is `${expression}`, where `expression` can be all kind of expression (e.g. `${100 + x}`).

The interpolation is used to insert the value of the `expression` converted to text (to string). Interpolations can be used only on two places: in text sections (e.g., `<h1>Hello ${name}!</h1>`) and in string literal expressions (e.g., `<#include "/footer/${company}.html">`).

A frequent mistake is the usage of interpolations in places where it shouldn't/can't be used. A typical bad usage is `<#if ${isBig}>Wow!</#if>`, which is syntactically WRONG. You should simply write `<#if isBig>Wow!</#if>`. Also, `<#if "${isBig}">Wow!</#if>` is WRONG, since the parameter value will be a string, and the `if` directive wants a boolean value, so it will cause a runtime error.

The result of the expression must be a string, number or date value. This is because only numbers and dates will be converted to string by the interpolation automatically, other types of values (such as booleans, sequences) must be converted to string "manually" somehow (see some advices later), or an error will stop the template processing.

##### Guide for inserting strings; don't forget escaping!

If the interpolation is in a text section (i.e., not in a string literal expression), the string that it will insert will be automatically escaped if an `escape` directive is in effect. If you are generating HTML it's strongly recommended to utilize this to prevent cross-site-scripting attacks and not-well-formed HTML pages. Here's a quick example:

    <#escape x as x?html>
      ...
      <p>Title: ${book.title}</p>
      <p>Description: <#noescape>${book.description}</#noescape></p>
      <h2>Comments:</h2>
      <#list comments as comment>
        <div class="comment">
          ${comment}
        </div>
      </#list>
      ...
    </#escape>

This example shows that when generating HTML you better put the whole template inside the `escape` directive. Thus, if the `book.title` contains `&`, it will be replaced with `&amp;` in the output so the page remains well-formed HTML. If a user comment contains tags like `<iframe>` (or any other element), they will become to `&lt;iframe&gt;` and like, rendering them harmless. But sometimes you really have HTML in the data-model, like let's assume `book.description` above is stored as HTML in the database, in which case you have to neutralize the enclosing `escape` with a `noescape`. Without the enclosing `escape`, the template would look like:

      ...
      <p>Title: ${book.title?html}</p>
      <p>Description: ${book.description}</p>
      <h2>Comments:</h2>
      <#list comments as comment>
        <div class="comment">
          ${comment?html}
        </div>
      </#list>
      ...

This does the same as the earlier example, but here you may forget some `?html`-s, which is a security risk. In the earlier example you may forget some `noescape`-s, which gives bad output too, but it's at least no a security risk.

##### Guide for inserting numerical values

If the expression evaluates to a number then the numerical value will be converted to string according the default number format. This may includes the maximum number of decimals, grouping, and like. Usually the programmer should set the default number format; the template author don't have to deal with it (but he can with the `number_format` setting; see in the documentation of `setting` directive). You can override the default number format for a single interpolation with the `string` built-in.

The decimal separator used (and other such symbols, like the group separator) depends on the current locale (language, country), that also should be set by the programmer. For example, this template:

    ${1.5}

will print something like this if the current locale is English:

    1.5

but if the current locale is Hungarian then it will print something like:

    1,5

since Hungarian people use comma as decimal separator.

You can modify the formatting for a single interpolation with the `string` built-in.

As you can see, interpolations print for human audience (by default at least), as opposed to ''computer audience''. In some cases this is not good, like when you print a database record ID-s as the part of an URL or as an invisible field value in a HTML form, or when you print CSS/JavaScript numerical literals, because these printed values will be read by computer programs and not by humans. Most computer programs are very particular about the format of the numbers, and understand only a kind of simple US number formatting. For that, use the `c` (stands for ''computer audience'') built-in, for example:

    <a href="/shop/productdetails?id=${product.id?c}">Details...</a>

##### Guide for inserting date/time values

If the expression evaluates to a date then the numerical value will be transformed to a text according to a default format. Usually the programmer should set the default format; you don't have to deal with it (but if you care, see the `date_format`, `time_format` and `datetime_format` settings in the documentation of the `setting` directive).

You can override the default formatting for a single interpolation with the `string` built-in.

To display a date as text, FreeMarker must know which parts of the date are in use, that is, if only the date part (year, month, day), or only the time part (hour, minute, second, millisecond), or both. Unfortunately, because of the technical limitations of Java platform, for some variables it is not possible to detect this automatically; ask the programmer if the data-model contains such problematic variables. If it is not possible to find out which parts of the date are in use, then you must help FreeMarker with the `date`, `time` and `datetime` built-ins, or it will stop with error.

##### Guide for inserting boolean values

An attempt to print boolean values with interpolation causes an error and aborts template processing. For example this will cause an error: `${a == 2}` and will not print ''true'' or something like that.

However, you can convert booleans to strings with the `?string` built-in. For example, to print the value of the "married" variable (assuming it's a boolean), you could write `${married?string("yes", "no")}`.

##### The exact conversion rules

For those who are interested, the exact rules of conversion from the expression value to string (which is then still subject to escaping) are these, in this order:

1. If the value is a number, then it is converted to string in the format specified with the `number_format` setting. So this usually formats for human audience, as opposed to computer audience.

2. Else if the value is whatever kind of date, time or date-time, then it is converted to string in the format specified with the `time_format`, `date_format`, or `datetime_format` setting, depending on whether the date information is time-only, date-only, or a date-time. If it can't be detected what kind of date it is (date vs time vs date-time), an error will occur.

3. Else if the value is a string, then there is no conversion.

4. Else if the engine is in classic compatibility mode:

   1. If the value is a boolean, true values are converted to "true", false values are converted to an empty string.

   2. If the expression is undefined (`null` or a variable is undefined), it is converted to an empty string.

   3. Else an error will abort the template processing.

5. Else an error will abort the template processing.

interpolation
${...}
template

### Miscellaneous

Do we need a short chapter on i18n/charset issues in general, with the introduction of FreeMarker facilities on this field at the end?

#### Defining your own directives

As far as template authors are concerned, user-defined directives can be defined using the `macro` directive. Java programmers who want to implement directives in Java Language, rather than in a template, should use `freemarker.template.TemplateDirectiveModel` (see more here...).

##### Basics

A macro is a template fragment associated with a variable. You can use that variable in your template as a user-defined directive, so it helps in repetitive tasks. For example, this creates a macro variable that prints a big ``Hello Joe!'':

    <#macro greet>
      <font size="+2">Hello Joe!</font>
    </#macro>

The `macro` directive itself does not print anything; it just creates the macro variable, so there will be a variable called `greet`. Things between the `<#macro greet>` and `</#macro>` (called macro definition body) will be executed only when you use the variable as directive. You use user-defined directives by writing `@` instead of `#` in the FTL tag. Use the variable name as the directive name. Also, the end-tag for user-defined directives is mandatory. So you use `greet` like this:

    <@greet></@greet>

But since `<anything></anything>` is equivalent with `<anything/>` you should use this shorter form (that is familiar for you if you know XML):

    <@greet/>

This will print:

      <font size="+2">Hello Joe!</font>

But macros can do much more, since the thing between `<#macro ...>` and `</#macro>` is a template fragment, thus it can contain interpolations (`${...}`) and FTL tags (e.g. `<#if ...>...</#if>`).

Programmers will say on `<@...>` that you call the macro.

defining macro

##### Parameters

Let's improve the `greet` macro so it can use arbitrary name, not only ``Joe''. For this purpose you can use parameters. You define the parameters after the name of the macro in the `macro` directive. Here we define one parameter for the `greet` macro, `person`:

    <#macro greet person>
      <font size="+2">Hello ${person}!</font>
    </#macro>

and then you can use this macro as:

    <@greet person="Fred"/> and <@greet person="Batman"/>

which is similar to HTML syntax. This will print:

      <font size="+2">Hello Fred!</font>
     and   <font size="+2">Hello Batman!</font>

As you can see, the actual value of the macro parameter is accessible in the macro definition body as a variable (`person`). As with predefined directives, the value of a parameter (the right side of `=`) is an FTL expression. Thus, unlike with HTML, the quotation marks around `"Fred"` and `"Batman"` are not optional. `<@greet person=Fred/>` would mean that you use the value of variable `Fred` for the `person` parameter, rather than the string `"Fred"`. Of course parameter value need not be a string, it can be number, boolean, hash, sequence, ...etc., also you can use complex expression on the left side of `=` (e.g. `someParam=(price + 50)*1.25`).

User-defined directives can have multiple parameters. For example, add a new parameter `color`:

    <#macro greet person color>
      <font size="+2" color="${color}">Hello ${person}!</font>
    </#macro>

and then you can use this macro like:

    <@greet person="Fred" color="black"/>

The order of parameters is not important, so this is equivalent with the previous:

    <@greet color="black" person="Fred"/>

When you call the macro, you can use only parameters that you have defined in the `macro` directive (in this case: `person` and `color`). So if you try `<@greet person="Fred" color="black" background="green"/>` then you will get an error, since you haven't mentioned parameter `background` in the `<#macro ...>`.

Also, you must give value for all parameters that you have defined for the macro. So if you try `<@greet person="Fred"/>` then you will get an error, since you forgot to specify the value of `color`. However, it often happens that you would specify the same value for a parameter in most cases, so you want to specify the value only when you want a different value for it than the usual. This can be achieved if you specify the parameter in the `macro` directive as `param_name=usual_value`. For example, you want to use `"black"` for `color` if you don't specify value for that parameter when you use the `greet` directive:

    <#macro greet person color="black">
      <font size="+2" color="${color}">Hello ${person}!</font>
    </#macro>

Now `<@greet person="Fred"/>` is OK, since it is equivalent with `<@greet person="Fred" color="black"/>`, thus the value of `color` parameter is known. If you want `"red"` for `color`, then you write `<@greet person="Fred" color="red"/>`, and this value will override the usual value specified with the `macro` directive, so the value of `color` parameter will be `"red"`.

Also, it is important to realize that -- according to the already explained FTL expression rules -- `someParam=foo` and `someParam="${foo}"` are very different. In the fist case, you use the value of variable `foo` as the value of the parameter. In the second case, you use a string literal with interpolation, so the value of the parameter will be a string -- in this case, the value of `foo` rendered to text -- regardless of the type (as number, date, etc.) of `foo`. Or, another example: `someParam=3/4` and `someParam="${3/4}"` are different. If the directive wants a numerical value for `someParam`, it will not like the second variation. Do not exchange these.

A very important aspect of macro parameters is that they are local variables. For more information about local variables please read:

##### Nested content

Custom directive can have nested content, similarly as predefined directives like `<#if ...>nested content</#if>` can have. For example, this creates a macro that draws borders around its nested content:

    <#macro border>
      <table border=4 cellspacing=0 cellpadding=4><tr><td>
        <#nested>
      </tr></td></table>
    </#macro>

The `<#nested>` directive executes the template fragment between the start-tag and end-tags of the directive. So if you do this:

    <@border>The bordered text</@border>

the output will be:

      <table border=4 cellspacing=0 cellpadding=4><tr><td>
        The bordered text
      </td></tr></table>

The `nested` directive can be called for multiple times, for example:

    <#macro do_thrice>
      <#nested>
      <#nested>
      <#nested>
    </#macro>
    <@do_thrice>
      Anything.
    </@do_thrice>

will print:

      Anything.
      Anything.
      Anything.

If you don't use the `nested` directive, then the nested content will not be executed. Thus, if you accidentally use the `greet` directive like this:

    <@greet person="Joe">
      Anything.
    </@greet>

then FreeMarker will not see this as an error, and simply prints:

    <font size="+2">Hello Joe!</font>

and the nested content will be ignored, since the `greet` macro never uses `nested` directive.

The nested content can be anything that is valid FTL, including other user-defined directives. Thus this is OK:

    <@border>
      <ul>
      <@do_thrice>
        <li><@greet person="Joe"/>
      </@do_thrice>
      </ul>
    </@border>

and will print:

      <table border=4 cellspacing=0 cellpadding=4><tr><td>
          <ul>
        <li><font size="+2">Hello Joe!</font>

        <li><font size="+2">Hello Joe!</font>

        <li><font size="+2">Hello Joe!</font>

      </ul>

      </tr></td></table>

The local variables of a macro are not visible in the nested content. Say, this:

    <#macro repeat count>
      <#local y = "test">
      <#list 1..count as x>
        ${y} ${count}/${x}: <#nested>
      </#list>
    </#macro>
    <@repeat count=3>${y!"?"} ${x!"?"} ${count!"?"}</@repeat>

will print this:

        test 3/1: ? ? ?
        test 3/2: ? ? ?
        test 3/3: ? ? ?

because the `y`, `x` and `count` are the local (private) variables of the macro, and are not visible from outside the macro definition. Furthermore, a different set of local variables is used for each macro call, so this will not cause confusion:

    <#macro test foo>${foo} (<#nested>) ${foo}</#macro>
    <@test foo="A"><@test foo="B"><@test foo="C"/></@test></@test>

and will print this:

    A (B (C () C) B) A

##### Macros with loop variables

Predefined directives like `list` can use so-called loop variables; you should read to understand loop variables.

User-defined directives can also have loop variables. For example, let's extend the `do_thrice` directive of the earlier examples so it exposes the current repetition number as a loop variable. As with the predefined directives (as `list`) the name of loop variables is given when you call the directive (as `foo` in `<#list foos as foo>...</#list>`), while the value of the variables is set by the directive itself.

    <#macro do_thrice>
      <#nested 1>
      <#nested 2>
      <#nested 3>
    </#macro>
    <@do_thrice ; x> <#-- user-defined directive uses ";" instead of "as" -->
      ${x} Anything.
    </@do_thrice>

This will print:

      1 Anything.
      2 Anything.
      3 Anything.

The syntactical rule is that you pass the actual value of the loop variable for a certain "loop" (i.e. repetition of the nested content) as the parameter of `nested` directive (of course the parameter can by arbitrary expression). The name of the loop variable is specified in the user-defined directive open tag (`<@...>`) after the parameters and a semicolon.

A macro can use more the one loop variable (the order of variables is significant):

    <#macro repeat count>
      <#list 1..count as x>
        <#nested x, x/2, x==count>
      </#list>
    </#macro>
    <@repeat count=4 ; c, halfc, last>
      ${c}. ${halfc}<#if last> Last!</#if>
    </@repeat>

The output will be:

      1. 0.5
      2. 1
      3. 1.5
      4. 2 Last!

It is not a problem if you specify different number of loop variables in the user-defined directive start-tag (that is, after the semicolon) than with the `nested` directive. If you specify less loop variables after the semicolon, then simply you will not see the last few values that the `nested` directive provides, since there is no loop variable to hold those values. So these are all OK:

    <@repeat count=4 ; c, halfc, last>
      ${c}. ${halfc}<#if last> Last!</#if>
    </@repeat>
    <@repeat count=4 ; c, halfc>
      ${c}. ${halfc}
    </@repeat>
    <@repeat count=4>
      Just repeat it...
    </@repeat>

If you specify more variables after the semicolon than with the `nested` directive, then the last few loop variables will not be created (i.e. will be undefined in the nested content).

loop variable

##### More about user-defined directives and macros

Now you may read the relevant parts of the FreeMarker Reference:

- user-defined directive call

- `macro` directive

You can define methods in FTL as well, see the `function` directive.

Also, you may interested in namespaces: . Namespaces help you to organize and reuse your commonly used macros.

macro
transform
custom directive
user-defined directive
directive user-defined
tag user-defined

#### Defining variables in the template

As we have described, a template can use the variables defined in the data-model. A template can also define variables outside the data-model for its own use. These temporary variables can be created and replaced using FTL directives. Note that each template processing job has its own private set of these variables that exists while the given page is being rendered. This variable set is initially empty, and will be thrown away when the template processing job has been finished.

You access a variable that you have defined in the template exactly as if it were a variable in the data-model root. The variable has precedence over any variable of the same name defined in the data-model. That is, if you define a variable called ``foo'' and coincidentally, there is a ``foo'' in the data-model as well, then the variable created in the template will hide (not overwrite!) the variable in the data-model root. For example, `${foo}` will print the value of the variable created in the template.

There are 3 kind of variables that are defined in a template:

- ``plain'' variables: They are accessible from everywhere in the template, or from the templates inserted with `include` directive. You can create and replace these variables with the `assign` or `macro` directives.

- Local variables: They can only be set inside a macro definition body, and are only visible from there. A local variable only exists for the duration of a macro call. You can create and replace local variables inside macro definition bodies with the `local` directive.

- Loop variables: Loop variables are created automatically by directives like `list`, and they only exist between the start-tag and end-tag of the directive. Macro parameters are local variables, not loop variables.

Example: Create and replace variables with `assign`:

    <#assign x = 1>  <#-- create variable x -->
    ${x}
    <#assign x = x + 3> <#-- replace variable x -->
    ${x}

Output:

    1
    4

Local variables hide (not overwrite) ``plain'' variables of the same name. Loop variables hide (not overwrite) local and ``plain'' variables of the same name. For example:

    <#assign x = "plain">
    1. ${x}  <#-- we see the plain var. here -->
    <@test/>
    6. ${x}  <#-- the value of plain var. was not changed -->
    <#list ["loop"] as x>
        7. ${x}  <#-- now the loop var. hides the plain var. -->
        <#assign x = "plain2"> <#-- replace the plain var, hiding does not mater here -->
        8. ${x}  <#-- it still hides the plain var. -->
    </#list>
    9. ${x}  <#-- the new value of plain var. -->

    <#macro test>
      2. ${x}  <#-- we still see the plain var. here -->
      <#local x = "local">
      3. ${x}  <#-- now the local var. hides it -->
      <#list ["loop"] as x>
        4. ${x}  <#-- now the loop var. hides the local var. -->
      </#list>
      5. ${x}  <#-- now we see the local var. again -->
    </#macro>

the output:

    1. plain
      2. plain
      3. local
        4. loop
      5. local
    6. plain
        7. loop
        8. loop
    9. plain2

An inner loop variable can hide an outer loop variable:

    <#list ["loop 1"] as x>
      ${x}
      <#list ["loop 2"] as x>
        ${x}
        <#list ["loop 3"] as x>
          ${x}
        </#list>
        ${x}
      </#list>
      ${x}
    </#list>

the output:

      loop 1
        loop 2
          loop 3
        loop 2
      loop 1

Note that the value of a loop variable is set by the directive invocation that has created it (the `<list ...>` tags in this case). There is no other way to change the value of a loop variable (say, you can't change its value with some kind of assignment directive). You can hide temporarily a loop variable with another loop variable though, as you have seen above.

Sometimes it happens that a variable hides the variable in the data-model with the same name, but you want to read the variable of the data-model. In this case you can use the special variable `globals`. For example, assume we have a variable called `user` in the data-model with value ``Big Joe'':

    <#assign user = "Joe Hider">
    ${user}          <#-- prints: Joe Hider -->
    ${.globals.user} <#-- prints: Big Joe -->

For information about syntax of variables please read:

variable
loop variable
local variable
temporary variable

#### Namespaces

When you run FTL templates, you have a (possibly empty) set of variables that you have created with `assign` and `macro` directives, as can be seen from the previous chapter. A set of variables like this is called a namespace. In simple cases you use only one namespace, the so-called main namespace. You don't realize this, since normally you use only this namespace.

But if you want to build reusable collection of macros, functions and other variables -- usually referred as library by lingo -- the usage of multiple namespaces becomes inevitable. Just consider if you have a big collection of macros, that you use in several projects, or even you want to share it with other people. It becomes impossible to be sure that the library does not have a macro (or other variable) with the same name as the name of a variable in the data-model, or with the same name as a the name of a variable in another library used in the template. In general, variables can clobber each other because of the name clashes. So you should use a separate namespace for the variables of each library.

##### Creating a library

Let's create a simple library. Assume you commonly need the variables `copyright` and `mail` (before you ask, macros are variables):

    <#macro copyright date>
      <p>Copyright (C) ${date} Julia Smith. All rights reserved.</p>
    </#macro>

    <#assign mail = "jsmith@acme.com">

Store the above in the file `lib/my_test.ftl` (in the directory where you store the templates). Assume you want to use this in `aWebPage.ftl`. If you use `<#include "/lib/my_test.ftl">` in the `aWebPage.ftl`, then it will create the two variables in the main namespace, and it is not good now, since you want them to be in a namespace that is used exclusively by the ``My Test Library''. Instead of `include` you have to use `import` directive. This directive is, at the first glance, similar to `include`, but it will create an empty namespace for `lib/my_test.ftl` and will execute that there. `lib/my_test.ftl` will find itself in an clean new world, where only the variables of data-model are present (since they are visible from everywhere), and will create the two variables in this new world. That's fine for now, but you want to access the two variables from `aWebPage.ftl`, and that uses the main namespace, so it can't see the variables of the other namespace. The solution is that the `import` directive not only creates the new namespace, but a new hash variable in the namespace used by the caller of `import` (the main namespace in this case), that will act as a gate into the newly created namespace. So this is how `aWebPage.ftl` will look like:

    <#import "/lib/my_test.ftl" as my> <#-- the hash called "my" will be the "gate" -->
    <@my.copyright date="1999-2002"/>
    ${my.mail}

Note how it accesses the variables in the namespace created for `/lib/my_test.ftl` using the newly created namespace accessing hash, `my`. This will print:

      <p>Copyright (C) 1999-2002 Julia Smith. All rights reserved.</p>
    jsmith@acme.com

If you would have a variable called `mail` or `copyright` in the main namespace, that would not cause any confusion, since the two templates use separated namespaces. For example, modify the `copyright` macro in `lib/my_test.ftl` to this:

    <#macro copyright date>
      <p>Copyright (C) ${date} Julia Smith. All rights reserved.
      <br>Email: ${mail}</p>
    </#macro>

and then replace `aWebPage.ftl` with this:

    <#import "/lib/my_test.ftl" as my>
    <#assign mail="fred@acme.com">
    <@my.copyright date="1999-2002"/>
    ${my.mail}
    ${mail}

and the output will be this:

      <p>Copyright (C) 1999-2002 Julia Smith. All rights reserved.
      <br>Email: jsmith@acme.com</p>
    jsmith@acme.com
    fred@acme.com

This is like that because when you have called the `copyright` macro, FreeMarker has temporarily switch to the namespace that was created by the `import` directive for `/lib/my_test.ftl`. Thus, the `copyright` macro always sees the `mail` variable that exists there, and not the other `mail` that exists in the main namespace.

##### Writing the variables of imported namespaces

Occasionally you may want to create or replace a variable in an imported namespace. You can do this with the `assign` directive, if you use its `namespace` parameter. For example, this:

    <#import "/lib/my_test.ftl" as my>
    ${my.mail}
    <#assign mail="jsmith@other.com" in my>
    ${my.mail}

will output this:

    jsmith@acme.com
    jsmith@other.com

##### Namespaces and data-model

The variables of the data-model are visible from everywhere. For example, if you have a variable called `user` in the data-model, `lib/my_test.ftl` will access that, exactly as `aWebPage.ftl` does:

    <#macro copyright date>
      <p>Copyright (C) ${date} ${user}. All rights reserved.</p>
    </#macro>

    <#assign mail = "${user}@acme.com">

If `user` is ``Fred'', then the usual example:

    <#import "/lib/my_test.ftl" as my>
    <@my.copyright date="1999-2002"/>
    ${my.mail}

will print this:

      <p>Copyright (C) 1999-2002 Fred. All rights reserved.</p>
    Fred@acme.com

Don't forget that the variables in the namespace (the variables you create with `assign` or `macro` directives) have precedence over the variables of the data-model when you are in that namespace. Thus, the contents of data-model does not interfere with the variables created by the library.

In some unusual applications you want to create variables in the template those are visible from all namespaces, exactly like the variables of the data-model. But you can't change the data-model with templates. Still, it is possible to achieve similar result with the `global` directive; read the reference for more details.

##### The life-cycle of namespaces

A namespace is identified by the path that was used with the `import` directive. If you try to `import` with the same path for multiple times, it will create the namespace and run the template specified by the path for the very first invocation of `import` only. The later `import`s with the same path will just create a ``gate'' hash to the same namespace. For example, let this be the `aWebPage.ftl`:

    <#import "/lib/my_test.ftl" as my>
    <#import "/lib/my_test.ftl" as foo>
    <#import "/lib/my_test.ftl" as bar>
    ${my.mail}, ${foo.mail}, ${bar.mail}
    <#assign mail="jsmith@other.com" in my>
    ${my.mail}, ${foo.mail}, ${bar.mail}

The output will be:

    jsmith@acme.com, jsmith@acme.com, jsmith@acme.com
    jsmith@other.com, jsmith@other.com, jsmith@other.com

since you see the same namespace through `my`, `foo` and `bar`.

Note that namespaces are not hierarchical, they exist independently of each other. That is, if you `import` namespace N2 while you are in name space N1, N2 will not be inside N1. N1 just gets a hash by which it can access N2. This is the same N2 namespace that you would access if, say, you `import` N2 when you are in the main namespace.

Each template processing job has its own private set of namespaces. Each template-processing job is a separated cosmos that exists only for the short period of time while the given page is being rendered, and then it vanishes with all its populated namespaces. Thus, whenever we say that ```import` is called for the first time'' and such, we are always talking in the context of a single template processing job.

##### Writing libraries for other people

If you have written a good quality library that can be useful for other people, you may want to make it available on the Internet (like on http://freemarker.org/libraries.html). To prevent clashes with the names of libraries used by other authors, and to make it easy to write libraries that import other published libraries, there is a de-facto standard that specifies the format of library paths. The standard is that the library must be available (importable) for templates and other libraries with a path like this:

`/lib/yourcompany.com/your_library.ftl`

For example if you work for Example Inc. that owns the www.example.com homepage, and you develop a widget library, then the path of the FTL file to import should be:

`/lib/example.com/widget.ftl`

Note that the www is omitted. The part after the 3rd slash can contain subdirectories such as:

`/lib/example.com/commons/string.ftl`

An important rule is that the path should not contain upper-case letters. To separate words, use `_`, as in `wml_form` (not `wmlForm`).

Note that if you do not develop the library for a company or organization, you should use the URL of the project homepage, such as `/lib/example.sourceforge.net/example.ftl`, or `/lib/geocities.com/jsmith/example.ftl`.

library path
namespaces
libraries

#### White-space handling

The control of the white-space in a template is a problem that to some extent haunts every template engine in the business.

Let see this template. I have marked the components of template with colors: text, interpolation, FTL tag. With the [BR]-s I visualize the line breaks.

    <p>List of users:[BR]
    <#assign users = [{"name":"Joe",        "hidden":false},[BR]
                      {"name":"James Bond", "hidden":true},[BR]
                      {"name":"Julia",      "hidden":false}]>[BR]
    <ul>[BR]
    <#list users as user>[BR]
      <#if !user.hidden>[BR]
      <li>${user.name}[BR]
      </#if>[BR]
    </#list>[BR]
    </ul>[BR]
    <p>That's all.

If FreeMarker were to output all text as is, the output would be:

    <p>List of users:[BR]
    [BR]
    <ul>[BR]
    [BR]
      [BR]
      <li>Joe[BR]
      [BR]
    [BR]
      [BR]
    [BR]
      [BR]
      <li>Julia[BR]
      [BR]
    [BR]
    </ul>[BR]
    <p>That's all.

You have a lot of unwanted spaces and line breaks here. Fortunately neither HTML nor XML is typically white-space sensitive, but this amount of superfluous white-space can be annoying, and needlessly increases the size of produced HTML. Of course, it is even bigger problem when outputting white-space-sensitive formats.

FreeMarker provides the following tools to cope with this problem:

- Tools to ignore certain white-space of the template files (parse time white-space removal):

  - White-space stripping: This feature automatically ignores typical superfluous white-space around FTL tags. It can be enabled or disabled on per template manner.

  - Trimmer directives: `t`, `rt`, `lt`. With these directives you can explicitly tell FreeMarker to ignore certain white-space. Read the reference for more information.

  - `ftl` parameter `strip_text`: This removes all top-level text from the template. It is useful for templates that contain macro definitions only (and some other non-outputting directives), because it removes the line-breaks that you use between the macro definitions and between the other top-level directives to improve the readability of the template.

- Tools that remove white-space from the output (on-the-fly white-space removal):

  - `compress` directive.

##### White-space stripping

If this feature is enabled for a template, then it automatically ignores (i.e. does not print to the output) two kind of typical superfluous white-space:

- Indentation white-space, and trailing white-space at the end of the line (includes the line break) will be ignored in lines that contains only FTL tags (e.g. `<@myMacro/>`, `<#if ...>`) and/or FTL comments (e.g. `<#-- blah -->`), apart from the the ignored white-space itself. For example, if a line contains only an `<#if ...>`, then the indentation before the tag and the line break after the tag will be ignored. However, if the line contains `<#if ...>x`, then the white-space in that line will not be ignored, because of the `x`, as that is not FTL tag. Note that according these rules, a line that contains `<#if ...><#list ...>` is subject to white-space ignoring, while a line that contains `<#if ...> <#list ...>` is not, because the white-space between the two FTL tags is embedded white-space, not indentation or trailing white-space.

- White-space sandwiched between the following directives is ignored: `macro`, `function`, `assign`, `global`, `local`, `ftl`, `import`, but only if there is only white-space and/or FTL comments between the directives. In practice it means that you can put empty lines between macro definitions and assignments as spacing for better readability, without printing needless empty lines (line breaks) to the output.

The output of the last example with white-space stripping enabled will be:

    <p>List of users:[BR]
    <ul>[BR]
      <li>Joe[BR]
      <li>Julia[BR]
    </ul>[BR]
    <p>That's all.

This is because after stripping the template becomes the following; the ignored text is not colored:

    <p>List of users:[BR]
    <#assign users = [{"name":"Joe",        "hidden":false},[BR]
                      {"name":"James Bond", "hidden":true},[BR]
                      {"name":"Julia",      "hidden":false}]>[BR]
    <ul>[BR]
    <#list users as user>[BR]
      <#if !user.hidden>[BR]
      <li>${user.name}[BR]
      </#if>[BR]
    </#list>[BR]
    </ul>[BR]
    <p>That's all.

White-space stripping can be enabled/disabled in per template manner with the `ftl` directive. If you don't specify this with the `ftl` directive, then white-space stripping will be enabled or disabled depending on how the programmer has configured FreeMarker. The factory default is white-space stripping enabled, and the programmers probably left it so (recommended). Note that enabling white-space stripping does not degrade the performance of template execution; white-space stripping is done during template loading.

White-space stripping can be disabled for a single line with the `nt` directive (for No Trim).

white-space removal stripping

##### Using compress directive

Another solution is to use the `compress` directive. As opposed to white-space stripping, this works directly on the generated output, not on the template. That is, it will investigate the printed output on the fly, and does not investigate the FTL program that creates the output. It aggressively removes indentations, empty lines and repeated spaces/tabs (for more information read the reference). So the output of:

    <#compress>
    <#assign users = [{"name":"Joe",        "hidden":false},
                      {"name":"James Bond", "hidden":true},
                      {"name":"Julia",      "hidden":false}]>
    List of users:
    <#list users as user>
      <#if !user.hidden>
      - ${user.name}
      </#if>
    </#list>
    That's all.
    </#compress>

will be:

    List of users:
    - Joe
    - Julia
    That's all.

Note that `compress` is totally independent of white-space stripping. So it is possible that the white-space of template is stripped, and later the produced output is `compress`-ed.

Also, by default a user-defined directve called `compress` is available in the data-model (due to backward compatibility). This is the same as the directive, except that you may optionally set the `single_line` parameter, which will remove all intervening line breaks. If you replace `<#compress>...</#compress>` on the last example with `<@compress single_line=true>...</@compress>`, then you get this output:

    List of users: - Joe - Julia That's all.

white-space removal compress
white-space removal

#### Alternative (square bracket) syntax

This feature exists since FreeMarker 2.3.4.

FreeMarker supports an alternative syntax, where `[` and `]` is used instead of `<` and `>` in FreeMarker directives and comments, for example:

- Calling predefined directive: `[#list animals as being]...[/#list]`

- Calling user-defined directive: `[@myMacro /]`

- Comment: `[#-- the comment --]`

To use the alternative syntax instead of the default one, start the template with the `ftl` directive using the alternative syntax. If you don't know what is the `ftl` directive, just start the template with `[#ftl]`, and remember that it should be the very first thing in the file (except that white-space can precede it). For example, this is how the last example of the Getting Started looks with the alternative syntax (assuming it's a complete template, not just a fragment):

    [#ftl]
    <p>We have these animals:
    <table border=1>
      <tr><th>Name<th>Price
      [#list animals as being]
      <tr>
        <td>
          [#if being.size = "large"]<b>[/#if]
          ${being.name}
          [#if being.size = "large"]</b>[/#if]
        <td>${being.price} Euros
      [/#list]
    </table>

The alternative (square bracket) and the default (angle bracket) syntax are mutually exclusive within a template. That is, either the whole template uses alternative syntax, or the whole template uses the default syntax. If the template uses alternative syntax, things like `<#if ...>` are count as static text, not as FTL tags. Similarly, if the template uses the default syntax, things like `[#if ...]` count as static text, not as FTL tags.

If you start the file with `[#ftl ...]` (where the `...` stands for the optional parameters; of course `[#ftl]` works too) the file will surely use the alternative (square bracket) syntax. If you start the file with `<#ftl ...>` the file will surely use the normal (angle bracket) syntax. If there is no `ftl` directive in the file, then the programmer decides what the syntax will be by configuring FreeMarker (programmers see `Configuration.setTagSyntax(int)` in the API javadocs). Most probably the programmers use the factory default however. The factory default in 2.3.x is using the normal syntax. The factory default in 2.4.x will be auto-detection, which means that the first FreeMarker tag determines the syntax (it can be anything, not just `ftl`).

alternative syntax
square bracket syntax

## Programmer's Guide

### Getting Started

Note that, if you are new to FreeMarker, you should read at least the before this chapter.

#### Create a configuration instance

First you have to create a `freemarker.template.Configuration` instance and adjust its settings. A `Configuration` instance is a central place to store the application level settings of FreeMarker. Also, it deals with the creation and caching of pre-parsed templates.

Probably you will do it only once at the beginning of the application (possibly servlet) life-cycle:

    Configuration cfg = new Configuration();
    // Specify the data source where the template files come from.
    // Here I set a file directory for it:
    cfg.setDirectoryForTemplateLoading(
            new File("/where/you/store/templates"));
    // Specify how templates will see the data-model. This is an advanced topic...
    // but just use this:
    cfg.setObjectWrapper(new DefaultObjectWrapper());

From now you should use this single configuration instance. Note however that if a system has multiple independent components that use FreeMarker, then of course they will use their own private `Configuration` instance.

configuration

#### Create a data-model

In simple cases you can build data-models using `java.lang` and `java.util` classes and custom Java Beans:

- Use `java.lang.String` for strings.

- Use `java.lang.Number` descents for numbers.

- Use `java.lang.Boolean` for boolean values.

- Use `java.util.List` or Java arrays for sequences.

- Use `java.util.Map` for hashes.

- Use your custom bean class for hashes where the items correspond to the bean properties. For example the `price` property of `product` can be get as `product.price`. (The actions of the beans can be exposed as well; see much later here)

For example, let's build the data-model of the first example of the Template Author's Guide. For convenience, here it is again:

    (root)
      |
      +- user = "Big Joe"
      |
      +- latestProduct
          |
          +- url = "products/greenmouse.html"
          |
          +- name = "green mouse"

This is the Java code fragment that builds this data-model:

    // Create the root hash
    Map root = new HashMap();
    // Put string ``user'' into the root
    root.put("user", "Big Joe");
    // Create the hash for ``latestProduct''
    Map latest = new HashMap();
    // and put it into the root
    root.put("latestProduct", latest);
    // put ``url'' and ``name'' into latest
    latest.put("url", "products/greenmouse.html");
    latest.put("name", "green mouse");

For the `latestProduct` you migh as well use a Java Bean that has `url` and `name` properties (that is, an object that has public `String getURL()` and `String getName()` methods); it's the same from viewpoint of the template.

data-model assembling with Java

#### Get the template

Templates are represented by `freemarker.template.Template` instances. Typically you obtain a `Template` instance from the `Configuration` instance. Whenever you need a template instance you can get it with its `getTemplate` method. Store the example template in the `test.ftl` file of the earlier set directory, then you can do this:

    Template temp = cfg.getTemplate("test.ftl");

When you call this, it will create a `Template` instance corresponds to `test.ftl`, by reading `/where/you/store/templates/test.ftl` and parsing (compile) it. The `Template` instance stores the template in the parsed form, and not as text.

`Configuration` caches `Template` instances, so when you get `test.ftl` again, it probably will not create new `Template` instance (thus doesn't read and parse the file), just returns the same instance as for the first time.

template Java side

#### Merging the template with the data-model

As we know, data-model + template = output, and we have a data-model (`root`) and a template (`temp`), so to get the output we have to merge them. This is done by the `process` method of the template. It takes the data-model root and a `Writer` as parameters. It writes the produced output to the `Writer`. For the sake of simplicity here I write to the standard output:

    Writer out = new OutputStreamWriter(System.out);
    temp.process(root, out);
    out.flush();

This will print to your terminal the output what you have seen in the first example of the Template Author's Guide.

Once you have obtained a `Template` instance, you can merge it with different data-models for unlimited times (`Template` instances are basically stateless). Also, the `test.ftl` file is accessed only while the `Template` instance is created, not when you call the process method.

output generate with Java
merging

#### Putting all together

This is a working source file assembled from the previous fragments. Don't forget to put `freemarker.jar` into the `CLASSPATH`.

    import freemarker.template.*;
    import java.util.*;
    import java.io.*;

    public class Test {

        public static void main(String[] args) throws Exception {

            /* ------------------------------------------------------------------- */
            /* You should do this ONLY ONCE in the whole application life-cycle:   */

            /* Create and adjust the configuration */
            Configuration cfg = new Configuration();
            cfg.setDirectoryForTemplateLoading(
                    new File("/where/you/store/templates"));
            cfg.setObjectWrapper(new DefaultObjectWrapper());

            /* ------------------------------------------------------------------- */
            /* You usually do these for many times in the application life-cycle:  */

            /* Get or create a template */
            Template temp = cfg.getTemplate("test.ftl");

            /* Create a data-model */
            Map root = new HashMap();
            root.put("user", "Big Joe");
            Map latest = new HashMap();
            root.put("latestProduct", latest);
            latest.put("url", "products/greenmouse.html");
            latest.put("name", "green mouse");

            /* Merge data-model with template */
            Writer out = new OutputStreamWriter(System.out);
            temp.process(root, out);
            out.flush();
        }
    }

I have suppressed the exceptions for the sake of simplicity. Don't do it in real products.

### The Data Model

This is just an introductory explanation. See the FreeMarker Java API documentation for more detailed information.

#### Basics

You have seen how to build a data-model in the Getting Started using the standard Java classes (`Map`, `String`, etc.). Internally, the variables available in the template are java objects that implement the `freemarker.template.TemplateModel` interface. But you could use standard java collections as variables in your data-model, because these were replaced with the appropriate `TemplateModel` instances behind the scenes. This facility is called object wrapping. The object wrapping facility can convert any kind of object transparently to the instances of classes that implement `TemplateModel` interface. This makes it possible, for example, to access `java.sql.ResultSet` as sequence variable in templates, or to access `javax.servlet.ServletRequest` objects as a hash variable that contains the request attributes, or even to traverse XML documents as FTL variables (see here). To wrap (convert) these objects, however, you need to plug the proper, so called, object wrapper implementation (possibly your custom implementation); this will be discussed later. The meat for now is that any object that you want to access from the templates, sooner or later must be converted to an object that implements `TemplateModel` interface. So first you should familiarize yourself with writing of `TemplateModel` implementations.

There is roughly one `freemarker.template.TemplateModel` descendant interface corresponding to each basic type of variable (`TemplateHashModel` for hashes, `TemplateSequenceModel` sequences, `TemplateNumberModel` for numbers, etc.). For example, if you want to expose a `java.sql.ResultSet` as a sequence for the templates, then you have to write a `TemplateSequenceModel` implementation that can read `java.sql.ResultSet`-s. We used to say on this, that you wrap the `java.sql.ResultSet` with your `TemplateModel` implementation, as basically you just encapsulate the `java.sql.ResultSet` to provide access to it with the common `TemplateSequenceModel` interface. Note that a class can implement multiple `TemplateModel` interfaces; this is why FTL variables can have multiple types (see: )

Note that a trivial implementation of these interfaces is provided with the `freemarker.template` package. For example, to convert a `String` to FTL string variable, you can use `SimpleScalar`, to convert a `java.util.Map` to FTL hash variable, you can use `SimpleHash`, etc.

An easy way to try your own `TemplateModel` implementation, is to create an instance of that, and drop it directly into the data-model (as `put` it into the root hash). The object wrapper will expose it untouched for the template, as it already implements `TemplateModel`, so no conversion (wrapping) needed. (This trick is also useful in cases when you do not want the object wrapper to try to wrap (convert) a certain object.)

object wrapper
wrapper
data-model assembling with Java, without object wrapper

#### Scalars

There are 4 scalar types:

- Boolean

- Number

- String

- Date

For each scalar type is a `TemplateTypeModel` interface, where `Type` is the name of the type. These interfaces define only one method: `type getAsType();`. This returns the value of the variable with the Java type (`boolean`, `Number`, `String` and `Date` respectively).

For historical reasons the interface for string scalars is called `TemplateScalarModel`, not `TemplateStringModel`.

A trivial implementation of these interfaces are available in `freemarker.template` package with `SimpleType` class name. However, there is no `SimpleBooleanModel`; to represent the boolean values you can use the `TemplateBooleanModel.TRUE` and `TemplateBooleanModel.FALSE` singletons.

For historical reasons the class for string scalars is called `SimpleScalar`, not `SimpleString`.

Scalars are immutable within FTL. When you set the value of a variable in a template, then you replace the `TemplateTypeModel` instance with another instance, and don't change the value stored in the original instance.

##### Difficulties with the date type

There is a complication around date types, because Java API usually does not differentiate `java.util.Date`-s that store only the date part (April 4, 2003), only the time part (10:19:18 PM), or both (April 4, 2003 10:19:18 PM). To display a date variable as text correctly, FreeMarker must know what parts of the `java.util.Date` stores meaningful information, and what parts are unused. Unfortunately, the only place where the Java API cleanly tells this, is with database handling (SQL), because databases typically has separated date, time and timestamp (aka date-time) types, and `java.sql` has 3 corresponding `java.util.Date` subclasses for them.

`TemplateDateModel` interface has two methods: `java.util.Date getAsDate()` and `int getDateType()`. A typical implementation of this interface, stores a `java.util.Date` object, plus an integer that tells the "database style type". The value of this integer must be a constant from the `TemplateDateModel` interface: `DATE`, `TIME`, `DATETIME` and `UNKNOWN`.

What is `UNKNOWN`? As we told earlier, `java.lang` and `java.util` classes are usually converted automatically into `TemplateModel` implementations, be so called object wrappers. If the object wrapper faces a `java.util.Date`, that is not an instance of a `java.sql` date class, it can't decide what the "database style type" is, so it uses `UNKNOWN`. Later, if the template has to use this variable, and the "database style type" is needed for the operation, it will stop with error. To prevent this, for the problematic variables the template author must help FreeMarker to decide the "database style type", by using the `date`, `time` or `datetime` built-ins. Note that if you use `string` built-in with format parameter, as `foo?string("MM/dd/yyyy")`, then FreeMarker don't need to know the "database style type".

date Java API related difficulties
time Java API related difficulties
scalar Java side
string Java side
number Java side
boolean Java side
date Java side
time Java side

#### Containers

These are hashes, sequences, and collections.

##### Hashes

Hashes are java objects that implement `TemplateHashModel` interface. `TemplateHashModel` contains two methods: `TemplateModel get(String key)`, which returns the subvariable of the given name, and `boolean isEmpty()`, which indicates if the hash has zero subvariable or not. The `get` method returns null if no subvariable with the given name exists.

The `TemplateHashModelEx` interface extends `TemplateHashModel`. It adds methods by which values and keys built-ins can enumerate the subvariables of the hash.

The commonly used implementation is `SimpleHash`, which implements `TemplateHashModelEx`. Internally it uses a `java.util.Hash` to store the subvariables. `SimpleHash` has methods by which you can add and remove subvariable. These methods should be used to initialize the variable directly after its creation.

Containers are immutable within FTL. That is, you can't add, replace or remove the subvariables they contain.

hash Java side

##### Sequences

Sequences are java objects that implement `TemplateSequenceModel`. It contains two methods: `TemplateModel get(int index)` and `int size()`.

The commonly used implementation is `SimpleSequence`. It uses internally a `java.util.List` to store its subvariables. `SimpleSequence` has methods by which you can add subvariables. These methods should be used to populate the sequence directly after its creation.

sequence Java side

##### Collections

Collections are java objects that implement the `TemplateCollectionModel` interface. That interface has one method: `TemplateModelIterator iterator()`. The `TemplateModelIterator` interface is similar to `java.util.Iterator`, but it returns `TemplateModels` instead of `Object`-s, and it can throw `TemplateModelException`s.

The commonly used implementation is `SimpleCollection`.

collection Java side
containers Java side

#### Methods

Method variables exposed to a template implement the `TemplateMethodModel` interface. This contains one method: `TemplateModel exec(java.util.List arguments)`. When you call a method with a method call expression, then the `exec` method will be called. The arguments parameter will contain the values of the FTL method call arguments. The return value of `exec` gives the value of the FTL method call expression.

The `TemplateMethodModelEx` interface extends `TemplateMethodModel`. It does not add any new methods. The fact that the object implements this marker interface indicates to the FTL engine that the arguments should be put to the `java.util.List` directly as `TemplateModel`-s. Otherwise they will be put to the list as `String`-s.

For obvious reasons there is no default implementation for these interfaces.

Example: This is a method, which returns the index within the second string of the first occurrence of the first string, or -1 if the second string doesn't contains the first.

    public class IndexOfMethod implements TemplateMethodModel {

        public TemplateModel exec(List args) throws TemplateModelException {
            if (args.size() != 2) {
                throw new TemplateModelException("Wrong arguments");
            }
            return new SimpleNumber(
                ((String) args.get(1)).indexOf((String) args.get(0)));
        }
    }

If you put an instance of this, say, into the root:

    root.put("indexOf", new IndexOfMethod());

then you can call it in the template:

    <#assign x = "something">
    ${indexOf("met", x)}
    ${indexOf("foo", x)}

and then the output will be:

    2
    -1

If you need to access the runtime FTL environment (read/write variables, get the current locale, etc.), you can get it with `Environment.getCurrentEnvironment()`.

method Java side

#### Directives

Java programmers can implement user-defined directives in Java using the `TemplateDirectiveModel` interface. See in the API documentation.

`TemplateDirectiveModel` was introduced in FreeMarker 2.3.11, replacing the soon to be depreciated `TemplateTransformModel`.

##### Example 1

We will implement a directive which converts all output between its start-tag and end-tag to upper case. Like, this template:

    foo
    <@upper>
      bar
      <#-- All kind of FTL is allowed here -->
      <#list ["red", "green", "blue"] as color>
        ${color}
      </#list>
      baaz
    </@upper>
    wombat

will output this:

    foo
      BAR
        RED
        GREEN
        BLUE
      BAAZ
    wombat

This is the source code of the directive class:

    package com.example;
    import java.io.IOException;
    import java.io.Writer;
    import java.util.Map;

    import freemarker.core.Environment;
    import freemarker.template.TemplateDirectiveBody;
    import freemarker.template.TemplateDirectiveModel;
    import freemarker.template.TemplateException;
    import freemarker.template.TemplateModel;
    import freemarker.template.TemplateModelException;

    /**
     *  FreeMarker user-defined directive that progressively transforms
     *  the output of its nested content to upper-case.
     *
     *
     *  <p><b>Directive info</b></p>
     *
     *  <p>Directive parameters: None
     *  <p>Loop variables: None
     *  <p>Directive nested content: Yes
     */
    public class UpperDirective implements TemplateDirectiveModel {

        public void execute(Environment env,
                Map params, TemplateModel[] loopVars,
                TemplateDirectiveBody body)
                throws TemplateException, IOException {
            // Check if no parameters were given:
            if (!params.isEmpty()) {
                throw new TemplateModelException(
                        "This directive doesn't allow parameters.");
            }
            if (loopVars.length != 0) {
                    throw new TemplateModelException(
                        "This directive doesn't allow loop variables.");
            }

            // If there is non-empty nested content:
            if (body != null) {
                // Executes the nested body. Same as <#nested> in FTL, except
                // that we use our own writer instead of the current output writer.
                body.render(new UpperCaseFilterWriter(env.getOut()));
            } else {
                throw new RuntimeException("missing body");
            }
        }

        /**
         * A {@link Writer} that transforms the character stream to upper case
         * and forwards it to another {@link Writer}.
         */
        private static class UpperCaseFilterWriter extends Writer {

            private final Writer out;

            UpperCaseFilterWriter (Writer out) {
                this.out = out;
            }

            public void write(char[] cbuf, int off, int len)
                    throws IOException {
                char[] transformedCbuf = new char[len];
                for (int i = 0; i < len; i++) {
                    transformedCbuf[i] = Character.toUpperCase(cbuf[i + off]);
                }
                out.write(transformedCbuf);
            }

            public void flush() throws IOException {
                out.flush();
            }

            public void close() throws IOException {
                out.close();
            }
        }

    }

Now we still need to create an instance of this class, and make this directive available to the template with the name "upper" (or with whatever name we want) somehow. A possible solution is to put the directive in the data-model:

    root.put("upper", new com.example.UpperDirective());

But typically it is better practice to put commonly used directives into the `Configuration` as shared variables.

It is also possible to put the directive into an FTL library (collection of macros and like in a template, that you `include` or `import` in other templates) using the `new` built-in:

    <#-- Maybe you have directives that you have implemented in FTL -->
    <#macro something>
      ...
    </#macro>

    <#-- Now you can't use <#macro upper>, but instead you can: -->
    <#assign upper = "com.example.UpperDirective"?new()>

##### Example 2

We will create a directive that executes its nested content again and again for the specified number of times (similarly to `list` directive), optionally separating the the output of the repetations with a `<hr>`-s. Let's call this directive "repeat". Example template:

    <#assign x = 1>

    <@repeat count=4>
      Test ${x}
      <#assign x = x + 1>
    </@repeat>

    <@repeat count=3 hr=true>
      Test
    </@repeat>

    <@repeat count=3; cnt>
      ${cnt}. Test
    </@repeat>

Output:

      Test 1
      Test 2
      Test 3
      Test 4

      Test
    <hr>  Test
    <hr>  Test

      1. Test
      2. Test
      3. Test

The class:

    package com.example;
    import java.io.IOException;
    import java.io.Writer;
    import java.util.Iterator;
    import java.util.Map;

    import freemarker.core.Environment;
    import freemarker.template.SimpleNumber;
    import freemarker.template.TemplateBooleanModel;
    import freemarker.template.TemplateDirectiveBody;
    import freemarker.template.TemplateDirectiveModel;
    import freemarker.template.TemplateException;
    import freemarker.template.TemplateModel;
    import freemarker.template.TemplateModelException;
    import freemarker.template.TemplateNumberModel;

    /**
     * FreeMarker user-defined directive for repeating a section of a template,
     * optionally with separating the output of the repetations with
     * <tt>&lt;hr></tt>-s.
     *
     *
     * <p><b>Directive info</b></p>
     *
     * <p>Parameters:
     * <ul>
     *   <li><code>count</code>: The number of repetations. Required!
     *       Must be a non-negative number. If it is not a whole number then it will
     *       be rounded <em>down</em>.
     *   <li><code>hr</code>: Tells if a HTML "hr" element could be printed between
     *       repetations. Boolean. Optional, defaults to <code>false</code>.
     * </ul>
     *
     * <p>Loop variables: One, optional. It gives the number of the current
     *    repetation, starting from 1.
     *
     * <p>Nested content: Yes
     */
    public class RepeatDirective implements TemplateDirectiveModel {

        private static final String PARAM_NAME_COUNT = "count";
        private static final String PARAM_NAME_HR = "hr";

        public void execute(Environment env,
                Map params, TemplateModel[] loopVars,
                TemplateDirectiveBody body)
                throws TemplateException, IOException {

            // ---------------------------------------------------------------------
            // Processing the parameters:

            int countParam = 0;
            boolean countParamSet = false;
            boolean hrParam = false;

            Iterator paramIter = params.entrySet().iterator();
            while (paramIter.hasNext()) {
                Map.Entry ent = (Map.Entry) paramIter.next();

                String paramName = (String) ent.getKey();
                TemplateModel paramValue = (TemplateModel) ent.getValue();

                if (paramName.equals(PARAM_NAME_COUNT)) {
                    if (!(paramValue instanceof TemplateNumberModel)) {
                        throw new TemplateModelException(
                                "The \"" + PARAM_NAME_HR + "\" parameter "
                                + "must be a number.");
                    }
                    countParam = ((TemplateNumberModel) paramValue)
                            .getAsNumber().intValue();
                    countParamSet = true;
                    if (countParam < 0) {
                        throw new TemplateModelException(
                                "The \"" + PARAM_NAME_HR + "\" parameter "
                                + "can't be negative.");
                    }
                } else if (paramName.equals(PARAM_NAME_HR)) {
                    if (!(paramValue instanceof TemplateBooleanModel)) {
                        throw new TemplateModelException(
                                "The \"" + PARAM_NAME_HR + "\" parameter "
                                + "must be a boolean.");
                    }
                    hrParam = ((TemplateBooleanModel) paramValue)
                            .getAsBoolean();
                } else {
                    throw new TemplateModelException(
                            "Unsupported parameter: " + paramName);
                }
            }
            if (!countParamSet) {
                    throw new TemplateModelException(
                            "The required \"" + PARAM_NAME_COUNT + "\" paramter"
                            + "is missing.");
            }

            if (loopVars.length > 1) {
                    throw new TemplateModelException(
                            "At most one loop variable is allowed.");
            }

            // Yeah, it was long and boring...

            // ---------------------------------------------------------------------
            // Do the actual directive execution:

            Writer out = env.getOut();
            if (body != null) {
                for (int i = 0; i < countParam; i++) {
                    // Prints a <hr> between all repetations if the "hr" parameter
                    // was true:
                    if (hrParam && i != 0) {
                        out.write("<hr>");
                    }

                    // Set the loop variable, if there is one:
                    if (loopVars.length > 0) {
                        loopVars[0] = new SimpleNumber(i + 1);
                    }

                    // Executes the nested body (same as <#nested> in FTL). In this
                    // case we don't provide a special writer as the parameter:
                    body.render(env.getOut());
                }
            }
        }

    }

##### Notices

It's important that a `TemplateDirectiveModel` object usually should not be stateful. The typical mistake is the storing of the state of the directive call execution in the fields of the object. Think of nested calls of the same directive, or directive objects used as shared variables accessed by multiple threads concurrently.

Unfortunatelly, `TemplateDirectiveModel`-s don't support passing parameters by position (rather than by name). This is fixed starting from FreeMarker 2.4.

directives Java side

#### Node variables

A node variable embodies a node in a tree structure. Node variables were introduced to help the handling of XML documents in the data-model, but they can be used for the modeling of other tree structures as well. For more information about nodes from the point of view of the template language read this earlier section.

A node variable has the following properties, provided by the methods of `TemplateNodeModel` interface:

- Basic properties:

  - `TemplateSequenceModel getChildNodes()`: A node has sequence of children (except if the node is a leaf node, in which case the method return an empty sequence or null). The child nodes should be node variables as well.

  - `TemplateNodeModel getParentNode()`: A node has exactly 1 parent node, except if the node is root node of the tree, in which case the method returns `null`.

- Optional properties. If a property does not make sense in the concrete use case, the corresponding method should return `null`:

  - `String getNodeName()`: The node name is the name of the macro, that handles the node when you use `recurse` and `visit` directives. Thus, if you want to use these directives with the node, the node name is required.

  - `String getNodeType()`: In the case of XML: `"element"`, `"text"`, `"comment"`, ...etc. This information, if available, is used by the `recurse` and `visit` directives to find the default handler macro for a node. Also it can be useful for other application specific purposes.

  - `String getNamespaceURI()`: The node namespace (has nothing to do with FTL namespaces used for libraries) this node belongs to. For example, in the case of XML, this is the URI of the XML namespace the element or attribute belongs to. This information, if available, is used by the `recurse` and `visit` directives to find the FTL namespaces that store the handler macros.

On the FTL side, the direct utilization of node properties is done with node built-ins, and with the `visit` and `recurse` macros.

In most use cases, variables that implement `TemplateNodeModel`, implement other interfaces as well, since node variable properties just provide the basic infrastructure for navigating between nodes. For a concrete example, see how FreeMarker deals with XML.

node Java side
tree nodes
trees

#### Object wrappers

When you add something to a container, it may receive any java object as a parameter, not necessarily a `TemplateModel`, as you could see in the FreeMarker API. This is because the container implementation can silently replace that object with the appropriate `TemplateModel` object. For example if you add a `String` to the container, perhaps it will be replaced with a `SimpleScalar` instance which stores the same text.

As for when the replacement occurs, it's the business of the container in question (i.e. the business of the class that implements the container interface), but it must happen at the latest when you get the subvariable, as the getter methods (according to the interfaces) return `TemplateModel`, not `Object`. For example, `SimpleHash`, `SimpleSequence` and `SimpleCollection` use the laziest strategy; they replace a non-`TemplateModel` subvariable with an appropriate `TemplateModel` object when you get the subvariable for the first time.

As for what java objects can be replaced, and with what `TemplateModel` implementations, it is either handled by the container implementation itself, or it delegates this to an `ObjectWrapper` instance. `ObjectWrapper` is an interface that specifies one method: `TemplateModel wrap(java.lang.Object obj)`. You pass in an `Object`, and it returns the corresponding `TemplateModel` object, or throws a `TemplateModelException` if this is not possible. The replacement rules are coded into the `ObjectWrapper` implementation.

The most important `ObjectWrapper` implementations that the FreeMarker core provides are:

- `ObjectWrapper.DEFAULT_WRAPPER`: It replaces `String` with `SimpleScalar`, `Number` with `SimpleNumber`, `List` and array with `SimpleSequence`, `Map` with `SimpleHash`, `Boolean` with `TemplateBooleanModel.TRUE` or `TemplateBooleanModel.FALSE`, W3C DOM nodes with `freemarker.ext.dom.NodeModel`. For Jython objects, this wrapper will invoke `freemarker.ext.jython.JythonWrapper`. For all other objects, it will invoke `BEANS_WRAPPER`.

- `ObjectWrapper.BEANS_WRAPPER`: It can expose java Bean properties and other members of arbitrary objects using Java reflection. At least in FreeMarker 2.3, it is a `freemarker.ext.beans.BeansWrapper` instance; there is a separated chapter about it.

For a concrete example, let's see how the `SimpleXxx` classes work. `SimpleHash`, `SimpleSequence` and `SimpleCollection` use `DEFAULT_WRAPPER` to wrap the subvariables (unless you pass in an alternative wrapper in their constructor). So this example demonstrates `DEFAULT_WRAPPER` in action:

    Map map = new HashMap();
    map.put("anotherString", "blah");
    map.put("anotherNumber", new Double(3.14));
    List list = new ArrayList();
    list.add("red");
    list.add("green");
    list.add("blue");

    SimpleHash root = new SimpleHash();  // will use the default wrapper
    root.put("theString", "wombat");
    root.put("theNumber", new Integer(8));
    root.put("theMap", map);
    root.put("theList", list);

Assuming that root is the data-model root, the resulting data-model is:

    (root)
     |
     +- theString = "wombat"
     |
     +- theNumber = 8
     |
     +- theMap
     |   |
     |   +- anotherString = "blah"
     |   |
     |   +- anotherNumber = 3.14
     |
     +- theList
         |
         +- (1st) = "red"
         |
         +- (2nd) = "green"
         |
         +- (3rd) = "blue"

Note that the `Object`-s inside `theMap` and `theList` are accessible as subvariables too. This is because when you, say, try to access `theMap.anotherString`, then the `SimpleHash` (which is used as root hash here) will silently replace the `Map` (`theMap`) with a `SimpleHash` instance that uses the same wrapper as the root hash, so when you try to access the `anotherString` subvariable of it, it will replace that with a `SimpleScalar`.

If you drop an ``arbitrary'' object into the data-model, `DEFAULT_WRAPPER` will invoke `BEANS_WRAPPER` to wrap the object:

    SimpleHash root = new SimpleHash();
    // expose a "simple" java objects:
    root.put("theString", "wombat");
    // expose an "arbitrary" java objects:
    root.put("theObject", new TestObject("green mouse", 1200));

Assuming this is `TestObject`:

    public class TestObject {
        private String name;
        private int price;

        public TestObject(String name, int price) {
            this.name = name;
            this.price = price;
        }

        // JavaBean properties
        // Note that public fields are not visible directly;
        // you must write a getter method for them.
        public String getName() {return name;}
        public int getPrice() {return price;}

        // A method
        public double sin(double x) {
            return Math.sin(x);
        }
    }

The data-model will be:

    (root)
     |
     +- theString = "wombat"
     |
     +- theObject
         |
         +- name = "green mouse"
         |
         +- price = 1200
         |
         +- number sin(number)

So we can merge it with this template:

    ${theObject.name}
    ${theObject.price}
    ${theObject.sin(123)}

Which will output:

    green mouse
    1200
    -0,45990349068959124

You have seen in earlier examples of this manual that we have used `java.util.HashMap` as root hash, and not `SimpleHash` or other FreeMarker specific class. It works because `Template.process(...)` automatically wraps the object you give as its data-model argument. It uses the object wrapper dictated by the `Configuration` level setting, `object_wrapper` (unless you explicitly specify an `ObjectWrapper` as its parameter). Thus, in simple FreeMarker application you need not know about `TemplateModel`-s at all. Note that the root need not be a `java.util.Map`. It can be anything that is wrapped so that it implements the `TemplateHashModel` interface.

The factory default value of the `object_wrapper` setting is `ObjectWrapper.DEFAULT_WRAPPER`. If you want to change it to, say, `ObjectWrapper.BEANS_WRAPPER`, you can configure the FreeMarker engine (before starting to use it from other threads) like this:

    cfg.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER);

Note that you can set any object here that implements interface `ObjectWrapper`, so you can set your custom implementation as well.

For `TemplateModel` implementations that wrap basic Java container types, as `java.util.Map`-s and `java.util.List`-s, the convention is that they use the same object wrapper to wrap their subvariables as their parent container does. Technically correctly said, they are instantiated by their parent container (so it has full control over the creation of them), and the parent container create them so they will use the same object wrapper as the parent itself. Thus, if `BEANS_WRAPPER` is used for the wrapping of the root hash, it will be used for the wrapping of the subvariables (and the subvariables of the subvariables, etc.) as well. This is exactly the same phenomenon as you have seen with `theMap.anotherString` earlier.

object wrapper
wrapper

### The Configuration

This is just an overview. See the FreeMarker Java API documentation for the details.

#### Basics

A configuration is an object that stores your common (application level) settings and defines certain variables that you want to be available in all templates. Also it deals with the creation and caching of `Template` instances. A configuration is a `freemarker.template.Configuration` instances, that you can create with its constructor. An application typically uses only a single shared `Configuration` instance.

Configurations are used by the `Template` methods, especially by `process` method. Each `Template` instance has exactly one `Configuration` instance associated with it, which is assigned to the `Template` instance by the `Template` constructor; you can specify a `Configuration` instance as its parameter. Usually you obtain `Template` instances with `Configuration.getTemplate` (not by directly calling the `Template` constructor), in which case the associated `Configuration` instance will be the one whose `getTemplate` method has been called.

#### Shared variables

Shared variables are variables that are defined for all templates. You can add shared variables to the configuration with the `setSharedVariable` methods:

    Configuration cfg = new Configuration();
    ...
    cfg.setSharedVariable("wrap", new WrapDirective());
    cfg.setSharedVariable("company", "Foo Inc.");  // Using ObjectWrapper.DEFAULT_WRAPPER

In all templates that use this configuration, an user-defined directive with name `wrap` and a string with name `company` will be visible in the data-model root, so you don't have to add them to the root hash again and again. A variable in the root object that you pass to the `Template.process` will hide the shared variable with the same name.

Never use `TemplateModel` implementation that is not thread-safe for shared variables, if the configuration is used by multiple threads! This is the typical situation for Servlet based Web sites.

Due to backward compatibility heritage, the set of shared variables is initially (i.e., for a new `Configuration` instance) not empty. It contains the following user-defined directives (they are "user-defined" in the sense that you use `@` to call them instead of `#`):

name | class
--- | ---
`capture_output` | `freemarker.template.utility.CaptureOutput`
`compress` | `freemarker.template.utility.StandardCompress`
`html_escape` | `freemarker.template.utility.HtmlEscape`
`normalize_newlines` | `freemarker.template.utility.NormalizeNewlines`
`xml_escape` | `freemarker.template.utility.XmlEscape`

shared variable

#### Settings

Settings are named values that influence the behavior of FreeMarker. Examples of settings are: `locale`, `number_format`

Settings stored in `Configuration` instance can be overridden in a `Template` instance. For example you set `"en_US"` for the `locale` setting in the configuration, then the `locale` in all templates that use this configuration will be `"en_US"`, except in templates where the locale was explicitly specified differently (see localization). Thus, values in a `Configuration` serve as defaults that can be overridden in a per template manner. The value comes from `Configuration` instance or `Template` instance can be further overridden for a single `Template.process` call. For each such call a `freemarker.core.Environment` object is created internally that holds the runtime environment of the template processing, including the setting values that were overridden on that level. The values stored there can even be changed during the template processing, so a template can set settings itself, like switching `locale` at the middle of the output.

This can be imagined as 3 layers (`Configuration`, `Template`, `Environment`) of settings, where the topmost layer that contains the value for a certain setting provides the effective value of that setting. For example (settings A to F are just imaginary settings for this example):

| Setting A | Setting B | Setting C | Setting D | Setting E | Setting F
--- | --- | --- | --- | --- | --- | ---
Layer 3: `Environment` | 1 | - | - | 1 | - | -
Layer 2: `Template` | 2 | 2 | - | - | 2 | -
Layer 1: `Configuration` | 3 | 3 | 3 | 3 | - | -

The effective value of settings will be: A = 1, B = 2, C = 3, D = 1, E = 2. The F setting is probably `null`, or it throws exception when you try to get it.

Let's see exactly how to set settings:

- `Configuration` layer: In principle you set the settings with the setter methods of the `Configuration` object, fore example:

      Configuration myCfg = new Configuration();
      myCfg.setLocale(java.util.Locale.ITALY);
      myCfg.setNumberFormat("0.####");

  You do it before you start to actually use the `Configuration` object (typically, when you initialize the application); you should treat the object as read-only after that.

  In practice, in most Web application frameworks you have to specify the setting in a framework-specific configuration file that require specifying setting as `String` name-value pairs (like in a `.properties` file). In that case the authors of the frameworks most probably use the `setSetting(String name, String value)` method of `Configuration`; see available setting names and the format of the values in the API doc of `setSetting`. Example for Spring Framework:

      <bean id="freemarkerConfig"
          class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
        <property name="freemarkerSettings">
          <props>
            <prop key="locale">it_IT</prop>
            <prop key="number_format">0.####</prop>
          </props>
        </property>
      </bean>

  Note that this kind of configuring (`String` key-value pairs) is unfortunately limited compared to directly using the API of `Configuration`.

- `Template` layer: You shouldn't set settings here, unless you manage the `Template` objects instead of a `freemarker.cache.TemplateCache`, in which case you should set the setting before the `Template` object is first used, and then treat the `Template` object as read-only.

- `Environment` layer: There are two ways doing it:

  - With Java API: Use the setter methods of the `Environment` object. Certainly you want to do that just before the processing of the template is started, and then you run into the problem that when you call `myTemplate.process(...)` it creates the `Environment` object internally and the immediately processes the template, so you had no chance. The solution is that this two steps can be separated like this:

        Environment env = myTemplate.createProcessingEnvironment(root, out);
        env.setLocale(java.util.Locale.ITALY);
        env.setNumberFormat("0.####");
        env.process();  // process the template

  - Directly in the Template: Use the `setting` directive, for example:

        <#setting locale="it_IT">
        <#setting number_format="0.####">

  There are no restriction regarding when can you change the settings in this layer.

To see the list of supported settings, please read the following parts of the FreeMarker Java API documentation:

- Setter methods of `freemarker.core.Configurable` for the settings that are in all three layers

- Setter methods of `freemarker.template.Configuration` for the settings that are available only in the `Configuration` layer

- `freemarker.core.Configurable.setSetting(String, String)` for settings that are available in all three layers and are writable with `String` key-value pairs.

- `freemarker.template.Configuration.setSetting(String, String)` for settings that are available only in the `Configuration` layer and are writable with `String` key-value pairs.

setting

#### Template loading

##### Template loaders

Template loaders are objects that load raw textual data based on abstract template paths like `"index.ftl"` or `"products/catalog.ftl"`. It is up to the concrete template loader object what source does it use to fetch the requested data (files in a directory, data base, etc.). When you call `cfg.getTemplate` (where `cfg` is a `Configuration` instance), FreeMarker ask the template loader you have set up for the `cfg` to return the text for the given template path, and then FreeMarker parses that text as template.

###### Built-in template loaders

You can set up three template loading methods in the `Configuration` using the following convenience methods. (Each method will create a template loader object internally and set up the `Configuration` instance to use that.)

    void setDirectoryForTemplateLoading(File dir);

or

    void setClassForTemplateLoading(Class cl, String prefix);

or

    void setServletContextForTemplateLoading(Object servletContext, String path);

The first method above sets an explicit directory on the file system from which to load templates. Needless to say perhaps, the `File` parameter must be an existing directory. Otherwise, an exception will be thrown.

The second call takes a `Class` as a parameter and a prefix. This is for when you want to load templates via the same mechanism that a java `ClassLoader` uses to load classes. This means that the class you pass in will be used to call `Class.getResource()` to find the templates. The `prefix` parameter is prepended to the name of the template. The classloading mechanism will very likely be the preferred means of loading templates for production code, since loading from the classpath mechanism is usually more foolproof than specifying an explicit directory location on the file system. It is also nicer in a final application to keep everything in a `.jar` file that the user can simply execute directly and have all the icons and text and everything else inside the `.jar` file.

The third call takes the context of your web application, and a base path, which is interpreted relative to the web application root directory (that's the parent of the `WEB-INF` directory). This loader will load the templates from the web application directory. Note that we refer to "directory" here although this loading method works even for unpacked `.war` files since it uses `ServletContext.getResource()` to access the templates. If you omit the second parameter (or use `""`), you can simply store the static files (`.html`, `.jpg`, etc.) mixed with the `.ftl` files, just `.ftl` files will be sent to the client processed. Of course, you must set up a Servlet for the `*.ftl` uri-pattern in `WEB-INF/web.xml` for this, otherwise the client will get the templates as is, and thus may see confidential content! You should not use empty path if this is a problem for your site, rather you should store the templates somewhere inside the `WEB-INF` directory, so the raw templates are never served accidentally. This mechanism will very likely be the preferred means of loading templates for servlet applications, since the templates can be updated without restarting the web application, while this often doesn't work with the class-loader mechanism.

###### Loading templates from multiple locations

If you need to load templates from multiple locations, you have to instantiate the template loader objects for every location, wrap them into a special template loader named `MultiTemplateLoader` and finally pass that loader to the `setTemplateLoader(TemplateLoader loader)` method of `Configuration`. Here's an example for loading templates from two distinct directories and with the class-loader:

    import freemarker.cache.*; // template loaders live in this package

    ...

    FileTemplateLoader ftl1 = new FileTemplateLoader(new File("/tmp/templates"));
    FileTemplateLoader ftl2 = new FileTemplateLoader(new File("/usr/data/templates"));
    ClassTemplateLoader ctl = new ClassTemplateLoader(getClass(), "");
    TemplateLoader[] loaders = new TemplateLoader[] { ftl1, ftl2, ctl };
    MultiTemplateLoader mtl = new MultiTemplateLoader(loaders);

    cfg.setTemplateLoader(mtl);

Now FreeMarker will try to load templates from `/tmp/templates` directory, and if it does not find the requested template there, it will try to load that from `/usr/data/templates`, and if it still does not find the requested template, then it tries to load that with the class-loader.

###### Loading templates from other sources

If none of the built-in class loaders are good for you, you will have to write your own class that implements the `freemarker.cache.TemplateLoader` interface and pass it to the `setTemplateLoader(TemplateLoader loader)` method of `Configuration`. Please read the API JavaDoc for more information.

If your template source accesses the templates through an URL, you needn't implement a `TemplateLoader` from scratch; you can choose to subclass `freemarker.cache.URLTemplateLoader` instead and just implement the `URL getURL(String templateName)` method.

###### The template path

It is up to the template loader how it interprets template paths. But to work together with other components there are restrictions regarding the format of the path. In general, it is strongly recommended that template loaders use URL-style paths. The path must not use `/`, `./` and `../` and `://` with other meaning as they have in URL paths (or in UN*X paths). The characters `*` and `?` are reserved. Also, the template loader must not want paths starting with `/`; FreeMarker will never call template loader with such path. Note that FreeMarker always normalizes the paths before passing them to the template loader, so the paths do not contain `/../` and such, and are relative to the imaginary template root directory.

Note that FreeMarker template loading always uses slash (not backslash) regardless of the host OS.

path
template path
template loaders

##### Template caching

FreeMarker caches templates (assuming you use the `Configuration` methods to create `Template` objects). This means that when you call `getTemplate`, FreeMarker not only returns the resulting `Template` object, but stores it in a cache, so when next time you call `getTemplate` with the same (or equivalent) path, it just returns the cached `Template` instance, and will not load and parse the template file again.

If you change the template file, then FreeMarker will re-load and re-parse the template automatically when you get the template next time. However, since checking if the file has been changed can be time consuming, there is a `Configuration` level setting called ``update delay''. This is the time that must elapse since the last checking for a newer version of a certain template before FreeMarker will check that again. This is set to 5 seconds by default. If you want to see the changes of templates immediately, set it to 0. Note that some template loaders may have problems with template updating. For example, class-loader based template loaders typically do not notice that you have changed the template file.

A template will be removed from the cache if you call `getTemplate` and FreeMarker realizes that the template file has been removed meanwhile. Also, if the JVM thinks that it begins to run out of memory, by default it can arbitrarily drop templates from the cache. Furthermore, you can empty the cache manually with the `clearTemplateCache` method of `Configuration`.

The actual strategy of when a cached template should be thrown away is pluggable with the `cache_storage` setting, by which you can plug any `CacheStorage` implementation. For most users `freemarker.cache.MruCacheStorage` will be sufficient. This cache storage implements a two-level Most Recently Used cache. In the first level, items are strongly referenced up to the specified maximum (strongly referenced items can't be dropped by the JVM, as opposed to softly referenced items). When the maximum is exceeded, the least recently used item is moved into the second level cache, where they are softly referenced, up to another specified maximum. The size of the strong and soft parts can be specified with the constructor. For example, set the size of the strong part to 20, and the size of soft part to 250:

    cfg.setCacheStorage(new freemarker.cache.MruCacheStorage(20, 250))

Or, since `MruCacheStorage` is the default cache storage implementation:

    cfg.setSetting(Configuration.CACHE_STORAGE_KEY, "strong:20, soft:250");

When you create a new `Configuration` object, initially it uses an `MruCacheStorage` where `maxStrongSize` is 0, and `maxSoftSize` is `Integer.MAX_VALUE` (that is, in practice, infinite). But using non-0 `maxStrongSize` is maybe a better strategy for high load servers, since it seems that, with only softly referenced items, JVM tends to cause just higher resource consumption if the resource consumption was already high, because it constantly throws frequently used templates from the cache, which then have to be re-loaded and and re-parsed.

caching
template caching
loading templates
template loading
storing templates

#### Error handling

##### The possible exceptions

The exceptions that can occur regarding FreeMarker could be classified like this:

- Exceptions occurring when you configure FreeMarker: Typically you configure FreeMarker only once in your application, when your application initializes itself. Of course, during this, exceptions can occur, as it is obvious from the FreeMarker API...

- Exceptions occurring when loading and parsing templates: When you call `Configuration.getTemplate(...)`, FreeMarker has to load the template file into the memory and parse it (unless the template is already cached in that `Configuration` object). During this, two kind of exceptions can occur:

  - `IOException` because the template file was not found, or other I/O problem occurred while trying to read it, for example you have no right to read the file, or there are disk errors. The emitter of these errors is the `TemplateLoader` object, which is plugged into the `Configuration` object. (For the sake of correctness: When I say ``file'' here, that's a simplification. For example, templates can be stored in a table of a relational database as well. This is the business of the `TemplateLoader`.)

  - `freemarker.core.ParseException` because the template file is syntactically incorrect according the rules of the FTL language. The point is that this error occurs when you obtain the `Template` object (`Configuration.getTemplate(...)`), and not when you execute (`Template.process(...)`) the template. This exception is an `IOException` subclass.

- Exceptions occurring when executing (processing) templates, that is, when you call `Template.process(...)`. Two kind of exceptions can occur:

  - `IOException` because there was an error when trying to write into the output writer.

  - `freemarker.template.TemplatException` because other problem occurred while executing the template. For example, a frequent error is when a template refers to a variable which is not existing. Be default, when a `TemplatException` occurs, FreeMarker prints the FTL error message and the stack trace to the output writer with plain text format, and then aborts the template execution by re-throwing the `TemplatException`, which then you can catch as `Template.process(...)` throws it. But this behavior can be customized. FreeMarker always logs `TemplatException`-s.

##### Customizing the behavior regarding TemplatException-s

`TemplateException`-s thrown during the template processing are handled by the `freemarker.template.TemplateExceptionHandler` object, which is plugged into the `Configuration` object with its `setTemplateExceptionHandler(...)` mehod. The `TemplateExceptionHandler` contains 1 method:

    void handleTemplateException(TemplateException te, Environment env, Writer out)
            throws TemplateException;

Whenever a `TemplateException` occurs, this method will be called. The exception to handle is passed with the `te` argument, the runtime environment of the template processing is accessible with the `env` argument, and the handler can print to the output using the `out` argument. If the method throws exception (usually it re-throws `te`), then the template processing will be aborted, and `Template.process(...)` will throw the same exception. If `handleTemplateException` doesn't throw exception, then template processing continues as if nothing had happen, but the statement that caused the exception will be skipped (see more later). Of course, the handler can still print an error indicator to the output.

In any case, before the `TemplateExceptionHandler` is invoked, FreeMarker will log the exception.

Let's see how FreeMarker skips ``statements'' when the error handler doesn't throw exception, through examples. Assume we are using this template exception handler:

    class MyTemplateExceptionHandler implements TemplateExceptionHandler {
        public void handleTemplateException(TemplateException te, Environment env, java.io.Writer out)
                throws TemplateException {
            try {
                out.write("[ERROR: " + te.getMessage() + "]");
            } catch (IOException e) {
                throw new TemplateException("Failed to print error message. Cause: " + e, env);
            }
        }
    }

    ...

    cfg.setTemplateExceptionHandler(new MyTemplateExceptionHandler());

If an error occurs in an interpolation which is not inside an FTL tag (that is, not enclosed into `<#...>` or `<@...>`), then the whole interpolation will be skipped. So this template (assuming that `badVar` is missing from the data-model):

    a${badVar}b

will print this if we use the `MyTemplateExceptionHandler`:

    a[ERROR: Expression badVar is undefined on line 1, column 4 in test.ftl.]b

This template will print the same (except that the column number will differ...):

    a${"moo" + badVar}b

since, as it was written, the whole interpolation is skipped if any error occurs inside it.

If an error occurs when evaluating the value of a parameter for a directive call, or if there are other problems with the parameter list, or if an error occurs when evaluating `exp` in `<@exp ...>`, or if the value of `exp` is not an user-defined directive, then the whole directive call is skipped. For example this:

    a<#if badVar>Foo</#if>b

will print this:

    a[ERROR: Expression badVar is undefined on line 1, column 7 in test.ftl.]b

Note that the error occurred in the `if` start-tag (`<#if badVar>`), but the whole directive call was skipped. Logically, the nested content (`Foo`) was skipped with this, since the nested content is handled (printed) by the enclosing directive (`if`).

The output will be the same with this (except that the column number will differ...):

    a<#if "foo${badVar}" == "foobar">Foo</#if>b

since, as it was written, the whole directive calling will be skipped if any error occurs during the parameter evaluation.

The directive call will not be skipped if the error occurs after the execution of the directive was already started. That is, if an error occurs in the nested content:

    a
    <#if true>
      Foo
      ${badVar}
      Bar
    </#if>
    c

or in the macro definition body:

    a
    <@test />
    b
    <#macro test>
      Foo
      ${badVar}
      Bar
    </#macro>

the output will be something like:

    a
      Foo
      [ERROR: Expression badVar is undefined on line 4, column 5 in test.ftl.]
      Bar
    c

FreeMarker comes with these prewritten error handlers:

- `TemplateExceptionHandler.DEBUG_HANDLER`: Prints stack trace (includes FTL error message and FTL stack trace) and re-throws the exception. This is the default handler (that is, it is initially prugged into all new `Configuration` objects).

- `TemplateExceptionHandler.HTML_DEBUG_HANDLER`: Same as `DEBUG_HANDLER`, but it formats the stack trace so that it will be readable with Web browsers. Recommended over `DEBUG_HANDLER` when you generate HTML pages.

- `TemplateExceptionHandler.IGNORE_HANDLER`: Simply suppresses all exceptions (but remember, FreeMarker will still log them). It does nothing to handle the event. It does not re-throw the exception.

- `TemplateExceptionHandler.RETHROW_HANDLER`: Simply re-throws all exceptions, it doesn't do anything else. This handler can be good for Web applications (assuming you don't want to continue template processing after exception), because it gives the most control to the Web application over page generation on error conditions (since FreeMarker doesn't print anything to the output about the error). For more information about handling errors in Web applications see the FAQ.

##### Explicit error handling in templates

Although it has nothing to do with the FreeMarker configuration (the topic of this chapter), for the sake of completeness it is mentioned here that you can handle errors directly in templates as well. This is usually a bad practice (try keep templates simple and non-technical), but nonetheless necessary sometimes:

- Handling missing/null variables:

- Surviving malfunctioning ``portlets'' and such expendable page sections:

error handling
exception handling
Configuration

### Miscellaneous

This is just an introductory guide. See the FreeMarker Java API documentation for the details.

#### Variables

This chapter explains what happens when a template tries to access a variable, and how the variables are stored.

When you call `Template.process` it will internally create an `Environment` object that will be in use until `process` returns. This object stores the runtime state of template processing. Among other things, it stores the variables created by the template with directives like `assign`, `macro`, `local` or `global`. It never tries to modify the data-model object that you pass to the `process` call, nor does it create or replace shared variables stored in the configuration.

When you try to read a variable, FreeMarker will seek the variable in this order, and stops when it finds a variable with the right name:

1. In the Environment:

   1. If you are in a loop, in the set of loop variables. Loop variables are the variables created by directives like `list`.

   2. If you are inside a macro, in the local variable set of the macro. Local variables can be created with the `local` directive. Also, the parameters of macros are local variables.

   3. In the current namespace. You can put variables into a namespace with the `assign` directive.

   4. In the set of variables created with `global` directive. FTL handles these variables as if they were normal members of the data-model. That is, they are visible in all namespaces, and you can access them as if they would be in the data-model.

2. In the data-model object you have passed to the `process` method

3. In the set of shared variables stored in the `Configuration`

In practice, from the viewpoint of template authors these 6 layers are only 4 layers, since from that viewpoint the last 3 layers (variables created with `global`, the actual data-model object, shared variables) together constitute the set of global variables.

Note that it is possible to get variables from a specific layer in FTL with special variables.

variables

#### Charset issues

FreeMarker, as most Java applications, works with "UNICODE text" (UTF-16). Nonetheless, there are situations when it must deal with charsets, because it has to exchange data with the outer world that may uses various charsets.

##### The charset of the input

When FreeMarker has to load a template file (or an unparsed text file), then it must know the charset of the file, since files are just raw byte arrays. You can use the `encoding` setting to specify the charset. This setting takes effect only when FreeMarker loads a template (parsed or unparsed) with the `getTemplate` method of `Configuration`. Note that the `include` directive uses this method internally, so the value of the `encoding` setting is significant for an already loaded template if the template contains `include` directive call.

The getter and setter method of the `encoding` setting is special in the first (configuration) layer. The getter method guesses the return value based on a `Locale` passed as parameter; it looks up the encoding in a table that maps locales to encodings (called encoding map), and if the locale was not found there, it returns the default encoding. You can fill the encoding map with the `setEncoding(Locale locale, String encoding)` method of the configuration; the encoding map is initially empty. The default encoding is initially the value of the `file.encoding` system property, but you can set a different default with the `setDefaultEncoding` method.

You can give the charset directly by overriding the `encoding` setting in the template layer or runtime environment layer (When you specify an encoding as the parameter of `getTemplate` method, you override the `encoding` setting in the template layer.). If you don't override it, the effective value will be what the `configuration.getEncoding(Locale)` method returns for the effective value of the `locale` setting.

Also, instead of relying on this charset guessing mechanism, you can specify the charset of the template in the template file itself, with the `ftl` directive.

You may wonder what charset you should choose for the templates. It primarily depends on the tools (as text editors) that you want to use to create and modify templates. In principle, using UTF-8 is the best, but currently (2004) only a few tools supports it, actually most of them doesn't even know about charsets. So in that case you should use the widely used charset of your language, which is probably also the default charset of you working environment.

Note that the charset of the template is independent from the charset of the output that the tempalte generates (unless the enclosing software deliberately sets the output charset to the same as the template charset).

##### The charset of the output

The `output_encoding` setting/variable and the `url` built-in is available since FreeMarker 2.3.1. It doesn't exist in 2.3.

In principle FreeMarker does not deal with the charset of the output, since it writes the output to a `java.io.Writer`. Since the `Writer` is made by the software that encapsulates FreeMarker (such as a Web application framework), the output charset is controlled by the encapsulating software. Still, FreeMarker has a setting called `output_encoding` (starting from FreeMarker version 2.3.1). The enclosing software should set this setting (to the charset that the `Writer` uses), to inform FreeMarker what charset is used for the output (otherwise FreeMarker can't find it out). Some features, such as the `url` built-in, and the `output_encoding` special variable utilize this information. Thus, if the enclosing software doesn't set this setting then FreeMarker features that need to know the output charset can't be used.

output encoding
output charset

If you write software that will use FreeMarker, you may wonder what output charset should you choose. Of course it depends on the consumer of the FreeMarker output, but if the consumer is flexible regarding this question, then the common practice is either using the charset of the template file for the output, or using UTF-8. Using UTF-8 is usually a better practice, because arbitrary text may comes from the data-model, which then possibly contains characters that couldn't be encoded with the charset of the template.

FreeMarker settings can be set for each individual template processing if you use `Template.createProcessingEnvironment(...)` plus `Environment.process(...)` instead of `Template.process(...)`. Thus, you can set the `output_encoding` setting for each template execution independently:

    Writer w = new OutputStreamWriter(out, outputCharset);
    Environment env = template.createProcessingEnvironment(dataModel, w);
    env.setOutputEncoding(outputCharset);
    env.process();

charset
encoding

#### Multithreading

In a multithreaded environment `Configuration` instances, `Template` instances and data-models should be handled as immutable (read-only) objects. That is, you create and initialize them (for example with `set...` methods), and then you don't modify them later (e.g. you don't call `set...`). This allows us to avoid expensive synchronized blocks in a multithreaded environment. Beware with `Template` instances; when you get a `Template` instance with `Configuration.getTemplate`, you may get an instance from the template cache that is already used by other threads, so do not call its `set...` methods (calling `process` is of course fine).

The above restrictions do not apply if you access all objects from the same single thread only.

It is impossible to modify the data-model object or a shared variable with FTL, unless you put methods (or other objects) into the data-model that do that. We discourage you from writing methods that modify the data-model object or the shared variables. Try to use variables that are stored in the environment object instead (this object is created for a single `Template.process` call to store the runtime state of processing), so you don't modify data that are possibly used by multiple threads. For more information read:

multithreading
thread-safety

#### Bean wrapper

The `freemarker.ext.beans.BeansWrapper` is an object wrapper that was originally added to FreeMarker so arbitrary POJO-s (Plain Old Java Objects) can be wrapped into `TemplateModel` interfaces. Since then it has becomed the normal way of doing things, and in fact the `DefaultObjectWrapper` itself is a `BeansWrapper` extension. So everything described here goes for the `DefaultObjectWrapper` too, except that the `DefaultObjectWrapper` will wrap `String`, `Number`, `Date`, `array`, `Collection` (like `List`), `Map`, `Boolean` and `Iterator` objects with the `freemarker.template.SimpleXxx` classes, and W3C DOM nodes with `freemarker.ext.dom.NodeModel` (more about wrapped W3C DOM...), so for those the above described rules doesn't apply.

You will want to use `BeansWrapper` instead of `DefaultObjectWrapper` when any of these stands:

- The `Collection`-s and `Map`-s of the model should be allowed to be modified during template execution. (`DefaultObjectWrapper` prevents that, since it creates a copy of the collections when they are wrapped, and the copies will be read-only.)

- If the identity of the `array`, `Collection` and `Map` objects must be kept when they are passed to a wrapped object's method in the template. That is, if those methods must get exactly the same object that was earlier wrapped.

- If the Java API of the earlier listed classes (`String`, `Map`, `List` ...etc) should be visible for the templates. Even with `BeansWrapper`, they are not visible by default, but it can be achieved by setting the exposure level (see later). Note that this is usually a bad practice; try to use the built-ins (like `foo?size`, `foo?upper`, `foo?replace('_', '-')` ...etc) instead of the Java API.

Below is a summary of the `TemplateModel`-s that the `BeansWrapper` creates. Let's assume that the object is called `obj` before wrapping, and `model` after wrapping for the sake of the following discussion.

##### TemplateHashModel functionality

Every object will be wrapped into a `TemplateHashModel` that will expose JavaBeans properties and methods of the object. This way, you can use `model.foo` in the template to invoke `obj.getFoo()` or `obj.isFoo()` methods. (Note that public fields are not visible directly; you must write a getter method for them.) Public methods are also retrievable through the hash model as template method models, therefore you can use the `model.doBar()` to invoke `object.doBar()`. More on this on discussion of method model functionality.

If the requested key can not be mapped to a bean property or method, the framework will attempt to locate the so-called "generic get method", that is a method with signature public `any-return-type get(String)` or public `any-return-type get(Object)` and invoke that method with the requested key. Note that this allows convenient access to mappings in a `java.util.Map` and similar classes - as long as the keys of the map are `String`s and some property or method name does not shadow the mapping. (There is a solution to avoid shadowing, read on.) Also note that the models for `java.util.ResourceBundle` objects use the `getObject(String)` as the generic get method.

If you call `setExposeFields(true)` on a `BeansWrapper` instance, it will also expose public, non-static fields of classes as hash keys and values. I.e. if `foo` is a public, non-static field of the class `Bar`, and `bar` is a template variable wrapping an instance of `Bar`, then `bar.foo` expression will evaluate as the value of the field `foo` of the `bar` object. The public fields in all superclasses of the class are also exposed.

##### A word on security

By default, you will not be able to access several methods that are considered not safe for templating. For instance, you can't use synchronization methods (`wait`, `notify`, `notifyAll`), thread and thread group management methods (`stop`, `suspend`, `resume`, `setDaemon`, `setPriority`), reflection (`Field` `setXxx` methods, `Method.invoke`, `Constructor.newInstance`, `Class.newInstance`, `Class.getClassLoader` etc.) and various dangerous methods in `System` and `Runtime` classes (`exec`, `exit`, `halt`, `load`, etc.). The `BeansWrapper` has several security levels (called "levels of method exposure"), and the default called `EXPOSE_SAFE` is probably suited for most applications. There is a no-safeguard level called `EXPOSE_ALL` that allows you to call even the above unsafe methods, and a strict level `EXPOSE_PROPERTIES_ONLY` that will expose only bean property getters. Finally, there is a level named `EXPOSE_NOTHING` that will expose no properties and no methods. The only data you will be able to access through hash model interface in this case are items in maps and resource bundles, as well as objects returned from a call to generic `get(Object)` or `get(String)` methods - provided the affected objects have such method.

##### TemplateScalarModel functionality

Models for `java.lang.String` objects will implement `TemplateScalarModel` whose `getAsString()` method simply delegates to `toString()`. Note that wrapping `String` objects into Bean wrappers provides much more functionality than just them being scalars: because of the hash interface described above, the models that wrap `String`s also provide access to all `String` methods (`indexOf`, `substring`, etc.).

##### TemplateNumberModel functionality

Model wrappers for objects that are instances of `java.lang.Number` implement `TemplateNumberModel` whose `getAsNumber()` method returns the wrapped number object. Note that wrapping `Number` objects into Bean wrappers provides much more functionality than just them being number models: because of the hash interface described above, the models that wrap `Number`s also provide access to all their methods.

##### TemplateCollectionModel functionality

Model wrappers for native Java arrays and all classes that implement `java.util.Collection` will implement `TemplateCollectionModel` and thus gain the additional capability of being usable through `list` directive.

##### TemplateSequenceModel functionality

Model wrappers for native Java arrays and all classes that implement `java.util.List` will implement `TemplateSequenceModel` and thus their elements will be accessible by index using the `model[i]` syntax. You can also query the length of the array or the size of the list using the `model?size` built-in.

Also, every method that takes a single parameter that is assignable through reflective method invocation from a `java.lang.Integer` (these are `int`, `long`, `float`, `double`, `java.lang.Object`, `java.lang.Number`, and `java.lang.Integer`) also implements this interface. What this means is that you have a convenient way for accessing the so-called indexed bean properties: `model.foo[i]` will translate into `obj.getFoo(i)`.

##### TemplateMethodModel functionality

All methods of an object are represented as `TemplateMethodModelEx` objects accessible using a hash key with method name on their object's model. When you call a method using `model.method(arg1, arg2, ...)` the arguments are passed to the method as template models. The method will first try to unwrap them - see below for details about unwrapping. These unwrapped arguments are then used for the actual method call. In case the method is overloaded, the most specific method will be selected using the same rules that are used by the Java compiler to select a method from several overloaded methods. In case that no method signature matches the passed parameters, or that no method can be chosen without ambiguity, a `TemplateModelException` is thrown.

Methods of return type `void` return `TemplateModel.NOTHING`, so they can be safely called with the `${obj.method(args)}` syntax.

Models for instances of `java.util.Map` also implement `TemplateMethodModelEx` as a means for invoking their `get()` method. As it was discussed previously, you can use the hash functionality to access the "get" method as well, but it has several drawbacks: it's slower because first property and method names are checked for the key; keys that conflict with property and method names will be shadowed by them; finally you can use `String` keys only with that approach. In contrast, invoking `model(key)` translates to `model.get(key)` directly: it's faster because there's no property and method name lookup; it is subject to no shadowing; and finally it works for non-String keys since the argument is unwrapped just as with ordinary method calls. In effect, `model(key)` on a `Map` is equal to `model.get(key)`, only shorter to write.

Models for `java.util.ResourceBundle` also implement `TemplateMethodModelEx` as a convenient way of resource access and message formatting. A single-argument call to a bundle will retrieve the resource with the name that corresponds to the `toString()` value of the unwrapped argument. A multiple-argument call to a bundle will also retrieve the resource with the name that corresponds to the `toString()` value of the unwrapped argument, but it will use it as a format pattern and pass it to `java.text.MessageFormat` using the unwrapped values of second and later arguments as formatting parameters. `MessageFormat` objects will be initialized with the locale of the bundle that originated them.

##### Unwrapping rules

When invoking a Java method from a template, its arguments need to be converted from template models back to Java objects. Assuming that the target type (the declared type of the method's formal parameter) is denoted as `T`, the following rules are tried in the following order:

- If the model is the null model for this wrapper, Java `null` is returned.

- If the model implements `AdapterTemplateModel`, the result of `model.getAdaptedObject(T)` is returned if it is instance of `T` or it is a number and can be converted to `T` using numeric coercion as described three bullets lower. All models created by the BeansWrapper are themselves AdapterTemplateModel implementations, so unwrapping a model that was created by BeansWrapper for an underlying Java object always yields the original Java object.

- If the model implements the deprecated `WrapperTemplateModel`, the result of `model.getWrappedObject()` is returned if it is instance of `T` or it is a number and can be converted to `T` using numeric coercion as described two bullets lower.

- If `T` is `java.lang.String`, then if model implements `TemplateScalarModel` its string value is returned. Note that if the model doesn't implement TemplateScalarModel we don't attempt to automatically convert the model to string using String.valueOf(model). You'll have to use the ?string built-in explicitly to pass non-scalars as strings.

- If `T` is a primitive numeric type or `java.lang.Number` is assignable from `T`, and model implements `TemplateNumberModel`, then its numeric value is returned if it is instance of `T` or its boxing type (if `T` is primitive type). Otherwise, if `T` is a built-in Java numeric type (primitive type or a standard subclass of `java.lang.Number`, including `BigInteger` and `BigDecimal`) a new object of class `T` or its boxing type is created with the number model's appropriately coerced value.

- If `T` is `boolean` or `java.lang.Boolean`, and model implements `TemplateBooleanModel`, then its boolean value is returned.

- If `T` is `java.util.Map` and the model implements `TemplateHashModel`, then a special Map representation of the hash model is returned.

- If `T` is `java.util.List` and the model implements `TemplateSequenceModel`, then a special List representation of the sequence model is returned.

- If `T` is `java.util.Set` and the model implements `TemplateCollectionModel`, then a special Set representation of the collection model is returned.

- If `T` is `java.util.Collection` or `java.lang.Iterable` and the model implements either `TemplateCollectionModel` or `TemplateSequenceModel`, then a special Set or List representation of the collection or sequence model (respectively) is returned.

- If `T` is a Java array type and the model implements `TemplateSequenceModel`, then a new array of the specified type is created and its elements unwrapped into the array recursively using the array's component type as `T`.

- If `T` is `char` or `java.lang.Character`, and model implements `TemplateScalarModel`, and its string representation contains exactly one character, then a `java.lang.Character` with that value is retured.

- If `java.util.Date` is assignable from `T`, and model implements `TemplateDateModel`, and its date value is instance of `T`, then its date value is returned.

- If model is a number model, and its numeric value is instance of `T`, the numeric value is returned. You can have a custom subclass of java.lang.Number that implements a custom interface, and T might be that interface. (*)

- If model is a date model, and its date value is instance of `T`, the date value is returned. Similar consideration as for (*)

- If model is a scalar model, and `T` is assignable from `java.lang.String`, the string value is returned. This covers cases when T is java.lang.Object, java.lang.Comparable, and java.io.Serializable (**)

- If model is a boolean model, and `T` is assignable from `java.lang.Boolean`, the boolean value is returned. Same as (**)

- If model is a hash model, and `T` is assignable from `freemarker.ext.beans.HashAdapter`, a hash adapter is returned. Same as (**)

- If model is a sequence model, and `T` is assignable from `freemarker.ext.beans.SequenceAdapter`, a sequence adapter is returned. Same as (**)

- If model is a collection model, and `T` is assignable from `freemarker.ext.beans.SetAdapter`, a set adapter for the collection is returned. Same as (**)

- If the model is instance of `T`, the model itself is returned. This covers the case where the method explicitly declared a FreeMarker-specific model interface, as well as allows returning directive, method and transform models when java.lang.Object is requested.

- An exception signifying no conversion is possible is thrown.

##### Accessing static methods

The `TemplateHashModel` returned from `BeansWrapper.getStaticModels()` can be used to create hash models for accessing static methods and fields of an arbitrary class.

    BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
    TemplateHashModel staticModels = wrapper.getStaticModels();
    TemplateHashModel fileStatics =
        (TemplateHashModel) staticModels.get("java.io.File");

And you will get a template hash model that exposes all static methods and static fields (both final and non-final) of the `java.lang.System` class as hash keys. Suppose that you put the previous model in your root model:

    root.put("File", fileStatics);

From now on, you can use `${File.SEPARATOR}` to insert the file separator character into your template, or you can even list all roots of your file system by:

    <#list File.listRoots() as fileSystemRoot>...</#list>

Of course, you must be aware of the potential security issues this model brings.

You can even give the template authors complete freedom over which classes' static methods they use by placing the static models hash into your template root model with

    root.put("statics", BeansWrapper.getDefaultInstance().getStaticModels());

This object exposes just about any class' static methods if it's used as a hash with class name as the key. You can then use expression like `${statics["java.lang.System"].currentTimeMillis()}` in your template. Note, however that this has even more security implications, as someone could even invoke `System.exit()` using this model if the method exposure level is weakened to `EXPOSE_ALL`.

Note that in above examples, we always use the default `BeansWrapper` instance. This is a convenient static wrapper instance that you can use in most cases. You are also free to create your own `BeansWrapper` instances and use them instead especially when you want to modify some of its characteristics (like model caching, security level, or the null model representation).

static method accessing from templates

##### Accessing enums

The `TemplateHashModel` returned from `BeansWrapper.getEnumModels()` can be used to create hash models for accessing values of enums on JRE 1.5 or later. (An attempt to invoke this method on an earlier JRE will result in an `UnsupportedOperationException`.)

    BeansWrapper wrapper = BeansWrapper.getDefaultInstance();
    TemplateHashModel enumModels = wrapper.getEnumModels();
    TemplateHashModel roundingModeEnums =
        (TemplateHashModel) enumModels.get("java.math.RoundingMode");

And you will get a template hash model that exposes all enum values of the `java.math.RoundingMode` class as hash keys. Suppose that you put the previous model in your root model:

    root.put("RoundingMode", roundingModeEnums);

From now on, you can use `RoundingMode.UP` as an expression to reference the `UP` enum value in your template.

You can even give the template authors complete freedom over which enum classes they use by placing the enum models hash into your template root model with

    root.put("enums", BeansWrapper.getDefaultInstance().getEnumModels());

This object exposes any enum class if it's used as a hash with class name as the key. You can then use expression like `${enums["java.math.RoundingMode"].UP}` in your template.

The exposed enum values can be used as scalars (they'll delegate to their `toString()` method), and can be used in equality and inequality comparisons as well.

Note that in above examples, we always use the default `BeansWrapper` instance. This is a convenient static wrapper instance that you can use in most cases. You are also free to create your own `BeansWrapper` instances and use them instead especially when you want to modify some of its characteristics (like model caching, security level, or the null model representation).

enum
wrapping reflection
wrapping beans
beans wrapping

#### Logging

FreeMarker integrates with the following logging packages: SLF4J, Apache Commons Logging, Log4J, Avalon LogKit, and `java.util.logging` (Java 1.4 and above). By default, FreeMarker will look for the following logging packages in this order, and will automatically use the first package it finds: [2.4 - un-remark this] SLF4J, Apache Commons Logging, Log4J, Avalon, `java.util.logging`. However, if you call the static `selectLoggerLibrary` method on the `freemarker.log.Logger` class with appropriate parameter and before using any FreeMarker classes that log messages, you can explicitly select a logger package, or even disable the logging. See the API documentation for more details.

Prior to FreeMarker 2.4, SLF4J and Apache Commons Logging aren't searched automatically due to backward compatibility constraints, so to use one of them you must do this:

    import freemarker.log.Logger;
    ...
        // IMPORTANT: This should be executed before using other FreeMarker classes!
        Logger.selectLoggerLibrary(Logger.LIBRARY_SLF4J);  // or Logger.LIBRARY_COMMONS
    ...

Doing this is recommended, because starting from 2.4 SLF4J will be used by default if present, otherwise Apache Commons Logging if present, otherwise Log4J if present, etc.

All log messages produced by FreeMarker are logged into the logger hierarchy whose top-level logger is named `freemarker`. Currently used loggers are:

Logger name | Purpose
--- | ---
`freemarker.beans` | Logs messages of the Beans wrapper module.
`freemarker.cache` | Logs messages related to template loading and caching.
`freemarker.runtime` | Logs template exceptions thrown during template processing.
`freemarker.runtime.attempt` | Logs template exceptions thrown during template processing, but caught by `attempt`/`recover` directives. Enable DEBUG severity to see the exceptions.
`freemarker.servlet` | Logs messages of the `FreemarkerServlet` class.
`freemarker.jsp` | Logs messages of the FreeMarker JSP support.

You can call the static `selectLoggerLibrary` method on the `freemarker.log.Logger` class and pass it a string that will be used to prefix the above mentioned logger names. This is useful if you want to have separate loggers on a per-web-application basis (assuming the application uses its own local `freemarker.jar`). Also, you can disable logging with `Logger.selectLoggerLibrary(Logger.LIBRARY_NONE)`. In any case, `selectLoggerLibrary` must be called early, before FreeMarker could log anything, or else it will not have (consistent) effect.

logging

#### Using FreeMarker with servlets

In a fundamental sense, using FreeMarker in the web application space is no different from anywhere else; FreeMarker writes its output to a `Writer` that you pass to the `Template.process` method, and it does not care if that `Writer` prints to the console or to a file or to the output stream of `HttpServletResponse`. FreeMarker knows nothing about servlets and Web; it just merges Java object with template files and generates text output from them. From here, it is up to you how to build a Web application around this.

But, probably you want to use FreeMarker with some already existing Web application framework. Many frameworks rely on the ``Model 2'' architecture, where JSP pages handle presentation. If you use such a framework (for example, Apache Struts), then read on. For other frameworks please refer to the documentation of the framework.

##### Using FreeMarker for ``Model 2''

Many frameworks follow the strategy that the HTTP request is dispatched to user-defined ``action'' classes that put data into `ServletContext`, `HttpSession` and `HttpServletRequest` objects as attributes, and then the request is forwarded by the framework to a JSP page (the view) that will generate the HTML page using the data sent with the attributes. This is often referred as Model 2.

With these frameworks you can simply use FTL files instead of JSP files. But, since your servlet container (Web application server), unlike with JSP files, does not know out-of-the-box what to do with FTL files, a little extra configuring is needed for your Web application:

1. Copy `freemarker.jar` (from the `lib` directory of the FreeMarker distribution) into the `WEB-INF/lib` directory of your Web application.

2. Insert the following section to the `WEB-INF/web.xml` file of your Web application (and adjust it if required):

    <servlet>
      <servlet-name>freemarker</servlet-name>
      <servlet-class>freemarker.ext.servlet.FreemarkerServlet</servlet-class>

      <!-- FreemarkerServlet settings: -->
      <init-param>
        <param-name>TemplatePath</param-name>
        <param-value>/</param-value>
      </init-param>
      <init-param>
        <param-name>NoCache</param-name>
        <param-value>true</param-value>
      </init-param>
      <init-param>
        <param-name>ContentType</param-name>
        <param-value>text/html; charset=UTF-8</param-value> <!-- Forces UTF-8 output encoding! -->
      </init-param>

      <!-- FreeMarker settings: -->
      <init-param>
        <param-name>template_update_delay</param-name>
        <param-value>0</param-value> <!-- 0 is for development only! Use higher value otherwise. -->
      </init-param>
      <init-param>
        <param-name>default_encoding</param-name>
        <param-value>ISO-8859-1</param-value> <!-- The encoding of the template files. -->
      </init-param>
      <init-param>
        <param-name>number_format</param-name>
        <param-value>0.##########</param-value>
      </init-param>

      <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
      <servlet-name>freemarker</servlet-name>
      <url-pattern>*.ftl</url-pattern>
    </servlet-mapping>

    ...

    <!--
      Prevent the visiting of MVC Views from outside the servlet container.
      RequestDispatcher.forward/include should and will still work.
      Removing this may open security holes!
    -->
    <security-constraint>
      <web-resource-collection>
        <web-resource-name>FreeMarker MVC Views</web-resource-name>
        <url-pattern>*.ftl</url-pattern>
      </web-resource-collection>
      <auth-constraint>
        <!-- Nobody is allowed to visit these -->
      </auth-constraint>
    </security-constraint>

After this, you can use FTL files (`*.ftl`) in the same manner as JSP (`*.jsp`) files. (Of course you can choose another extension besides `ftl`; it is just the convention)

How does it work? Let's examine how JSP-s work. Many servlet container handles JSP-s with a servlet that is mapped to the `*.jsp` request URL pattern. That servlet will receive all requests where the request URL ends with `.jsp`, find the JSP file based on the request URL, and internally compiles it to a `Servlet`, and then call the generated servlet to generate the page. The `FreemarkerServlet` mapped here to the `*.ftl` URL pattern does the same, except that FTL files are not compiled to `Servlet`-s, but to `Template` objects, and then the `process` method of `Template` will be called to generate the page.

For example, instead of this JSP file (note that it heavily uses Struts tag-libs to save designers from embedded Java monsters):

    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
    <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>

    <html>
    <head><title>Acmee Products International</title>
    <body>
      <h1>Hello <bean:write name="user"/>!</h1>
      <p>These are our latest offers:
      <ul>
        <logic:iterate name="latestProducts" id="prod">
          <li><bean:write name="prod" property="name"/>
            for <bean:write name="prod" property="price"/> Credits.
        </logic:iterate>
      </ul>
    </body>
    </html>

you can use this FTL file (use `ftl` file extension instead of `jsp`):

    <html>
    <head><title>Acmee Products International</title>
    <body>
      <h1>Hello ${user}!</h1>
      <p>These are our latest offers:
      <ul>
        <#list latestProducts as prod>
          <li>${prod.name} for ${prod.price} Credits.
        </#list>
      </ul>
    </body>
    </html>

In FreeMarker `<html:form action="/query">...</html:form>` is just static text, so it is printed to the output as is, like any other XML or HTML markup. JSP tags are just FreeMarker directives, nothing special, so you use FreeMarker syntax for calling them, not JSP syntax: `<@html.form action="/query">...</@html.form>`. Note that in the FreeMarker syntax you don't use `${...}` in parameters as in JSP, and you don't quote the parameter values. So this is WRONG:

    <#-- WRONG: -->
    <@my.jspTag color="${aVariable}" name="aStringLiteral"
                width="100" height=${a+b} />

and this is good:

    <#-- Good: -->
    <@my.jspTag color=aVariable name="aStringLiteral"
                width=100 height=a+b />

In both templates, when you refer to `user` and `latestProduct`, it will first try to find a variable with that name that was created in the template (like `prod`; if you master JSP: a page scope attribute). If that fails, it will try to look up an attribute with that name in the `HttpServletRequest`, and if it is not there then in the `HttpSession`, and if it still doesn't find it then in the `ServletContext`. In the case of FTL this works because `FreemarkerServlet` builds the data-model from the attributes of the mentioned 3 objects. That is, in this case the root hash is not a `java.util.Map` (as it was in some example codes in this manual), but `ServletContext`+`HttpSession`+`HttpServletRequest`; FreeMarker is pretty flexible about what the data-model is. So if you want to put variable `"name"` into the data-model, then you call `servletRequest.setAttribute("name", "Fred")`; this is the logic of Model 2, and FreeMarker adapts itself to it.

`FreemarkerServlet` also puts 3 hashes into the data-model, by which you can access the attributes of the 3 objects directly. The hash variables are: `Request`, `Session`, `Application` (corresponds to `ServletContext`). It also exposes another hash named `RequestParameters` that provides access to the parameters of the HTTP request.

`FreemarkerServlet` has various init-params. It can be set up to load templates from an arbitrary directory, from the classpath, or relative to the Web application directory. You can set the charset used for templates. You can set up what object wrapper do you want to use. Etc.

`FreemarkerServlet` is easily tailored to special needs through subclassing. Say, if you need to have additional variables available in your data-model for all templates, subclass the servlet and override the `preTemplateProcess()` method to shove any additional data you need into the model before the template gets processed. Or subclass the servlet, and set these globally available variables as shared variables in the `Configuration`.

For more information please read the Java API documentation of the class.

##### Including content from other web application resources

You can use the `<@include_page path="..."/>` custom directive provided by the `FreemarkerServlet` (since 2.3.15) to include the contents of another web application resource into the output; this is often useful to integrate output of JSP pages (living alongside the FreeMarker templates in the same web server) into the FreeMarker template output. Using:

    <@include_page path="path/to/some.jsp"/>

is identical to using this tag in JSP:

    <jsp:include page="path/to/some.jsp">

`<@include_page ...>` is not to be confused with `<#include ...>`, as the last is for including FreeMarker templates without involving the Servlet container. An `<#include ...>`-ed template shares the template processing state with the including template, such as the data-model and the template-language variables, while `<@include_page ...>` starts an independent HTTP request processing.

Some Web Application Frameworks provide their own solution for this, in which case you possibly should use that instead. Also some Web Application Frameworks don't use `FreemarkerServlet`, so `include_page` is not available.

The path can be relative or absolute. Relative paths are interpreted relative to the URL of the current HTTP request (one that triggered the template processing), while absolute paths are absolute in the current servlet context (current web application). You can not include pages from outside the current web application. Note that you can include any page, not just a JSP page; we just used page with path ending in `.jsp` as an illustration.

In addition to the `path` parameter, you can also specify an optional parameter named `inherit_params` with a boolean value (defaults to true when not specified) that specifies whether the included page will see the HTTP request parameters of the current request or not.

Finally, you can specify an optional parameter named `params` that specifies new request parameters that the included page will see. In case inherited parameters are passed too, the values of specified parameters will get prepended to the values of inherited parameters of the same name. The value of `params` must be a hash, with each value in it being either a string, or a sequence of strings (if you need multivalued parameters). Here's a full example:

    <@include_page path="path/to/some.jsp" inherit_params=true params={"foo": "99", "bar": ["a", "b"]}/>

This will include the page `path/to/some.jsp`, pass it all request parameters of the current request, except for "foo" and "bar", which will be set to "99" and multi-value of "a", "b", respectively. In case the original request already had values for these parameters, the new values will be prepended to the existing values. I.e. if "foo" had values "111" and "123", then it will now have values "99", "111", "123".

It is in fact possible to pass non-string values for parameter values within `params`. Such a value will be converted to a suitable Java object first (i.e. a Number, a Boolean, a Date, etc.), and then its Java `toString()` method will be used to obtain the string value. It is better to not rely on this mechanism, though, and instead explicitly ensure that parameter values that aren't strings are converted to strings on the template level where you have control over formatting using the `?string` and `?c` built-ins.

include servlet
include JSP
servlet include
JSP include

##### Using JSP custom tags in FTL

`FreemarkerServlet` puts a hash `JspTaglibs` into the data-model, what you can use to access JSP taglibs. The JSP custom tags will be accessible as plain user-defined directives. For example, this is a JSP file that uses some Struts tags:

    <%@page contentType="text/html;charset=ISO-8859-2" language="java"%>
    <%@taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
    <%@taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>

    <html>
      <body>
        <h1><bean:message key="welcome.title"/></h1>
        <html:errors/>
        <html:form action="/query">
          Keyword: <html:text property="keyword"/><br>
          Exclude: <html:text property="exclude"/><br>
          <html:submit value="Send"/>
        </html:form>
      </body>
    </html>

And this is the (near) equivalent FTL:

    <#assign html=JspTaglibs["/WEB-INF/struts-html.tld"]>
    <#assign bean=JspTaglibs["/WEB-INF/struts-bean.tld"]>

    <html>
      <body>
        <h1><@bean.message key="welcome.title"/></h1>
        <@html.errors/>
        <@html.form action="/query">
          Keyword: <@html.text property="keyword"/><br>
          Exclude: <@html.text property="exclude"/><br>
          <@html.submit value="Send"/>
        </@html.form>
      </body>
    </html>

Since JSP custom tags are written to operate in JSP environment, they assume that variables (often referred as ``beans'' in JSP world) are stored in 4 scopes: page scope, request scope, session scope and application scope. FTL has no such notation (the 4 scopes), but `FreemarkerServlet` provides emulated JSP environment for the custom JSP tags, which maintains correspondence between the ``beans'' of JSP scopes and FTL variables. For the custom JSP tags, the request, session and application scopes are exactly the same as with real JSP: the attributes of the `javax.servlet.ServletContext`, `HttpSession` and `ServletRequest` objects. From the FTL side you see these 3 scopes together as the data-model, as it was explained earlier. The page scope corresponds to the FTL global variables (see the `global` directive). That is, if you create a variable with the `global` directive, it will be visible for the custom tags as page scope variable through the emulated JSP environment. Also, if a JSP-tag creates a new page scope variable, the result will be the same as if you create a variable with the `global` directive. Note that the variables in the data-model are not visible as page-scope attributes for the JSP tags, despite that they are globally visible, since the data-model corresponds to the request, session and application scopes, not the page-scope.

On JSP pages you quote all attribute values, it does not mater if the type of the parameter is string or boolean or number. But since custom tags are accessible in FTL templates as user-defined FTL directives, you have to use the FTL syntax rules inside the custom tags, not the JSP rules. So when you specify the value of an ``attribute'', then on the right side of the `=` there is an FTL expression. Thus, you must not quote boolean and numerical parameter values (e.g. `<@tiles.insert page="/layout.ftl" flush=true/>`), or they are interpreted as string values, and this will cause a type mismatch error when FreeMarker tries to pass the value to the custom tag that expects non-string value. Also note, that naturally, you can use any FTL expression as attribute value, such as variables, calculated values, etc. (e.g. `<@tiles.insert page=layoutName flush=foo && bar/>`).

FreeMarker does not rely on the JSP support of the servlet container in which it is run when it uses JSP taglibs since it implements its own lightweight JSP runtime environment. There is only one small detail to pay attention to: to enable the FreeMarker JSP runtime environment to dispatch events to JSP taglibs that register event listeners in their TLD files, you should add this to the `WEB-INF/web.xml` of your Web application:

    <listener>
      <listener-class>freemarker.ext.jsp.EventForwarding</listener-class>
    </listener>

Note that you can use JSP taglibs with FreeMarker even if the servlet container has no native JSP support, just make sure that the `javax.servlet.jsp.*` packages for JSP 1.2 (or later) are available to your Web application. If your servlet container comes with JSP 1.1, then you have to obtain the following six classes (for example you can extract them from the jar-s of Tomcat 5.x or Tomcat 4.x), and copy them into your webapp's `WEB-INF/classes/...` directory: `javax.servlet.jsp.tagext.IterationTag`, `javax.servlet.jsp.tagext.TryCatchFinally`, `javax.servlet.ServletContextListener`, `javax.servlet.ServletContextAttributeListener`, `javax.servlet.http.HttpSessionAttributeListener`, `javax.servlet.http.HttpSessionListener`. But beware, since containers that come with JSP 1.1 usually use earlier Serlvet versions than 2.3, event listeners will not be supported, and thus JSP 1.2 taglibs that register event listeners will not work properly.

As of this writing, JSP features up to JSP 2.1 are implemented, except the "tag files" feature of JSP 2 (i.e., custom JSP tags implemented in JSP language). The tag files had to be compiled to Java classes to be usable under FreeMarker.

JSP taglib
custom tags
taglib

##### Embed FTL into JSP pages

There is a taglib that allows you to put FTL fragments into JSP pages. The embedded FTL fragment can access the attributes (Beans) of the 4 JSP scopes. You can find a working example and the taglib in the FreeMarker distribution.

JSP taglib
Servlet
HTTP
JSP
Model 2
Struts
Web application framework

#### Configuring security policy for FreeMarker

When FreeMarker is used in a Java virtual machine with a security manager installed, you have to grant it few permissions to ensure it operates properly. Most notably, you need these entries to your security policy file for `freemarker.jar`:

    grant codeBase "file:/path/to/freemarker.jar"
    {
      permission java.util.PropertyPermission "file.encoding", "read";
      permission java.util.PropertyPermission "freemarker.*", "read";
    }

Additionally, if you are loading templates from a directory, you need to give FreeMarker permissions to read files from that directory using the following permission:

    grant codeBase "file:/path/to/freemarker.jar"
    {
      ...
      permission java.io.FilePermission "/path/to/templates/-", "read";
    }

Finally, if you're just using the default template loading mechanism which loads templates from the current directory, then specify these permissions additionally: (note that the expression `${user.dir}` will be evaluated at run time by the policy interpreter, pretty much as if it were a FreeMarker template)

    grant codeBase "file:/path/to/freemarker.jar"
    {
      ...
      permission java.util.PropertyPermission "user.dir", "read";
      permission java.io.FilePermission "${user.dir}/-", "read";
    }

Naturally, if you're running under Windows, use double backslash instead of a single slash for separating directory components in paths.

security

#### Legacy XML wrapper implementation

The legacy XML wrapper is deprecated. FreeMarker 2.3 has introduced support for a new XML processing model. To support this, a new XML wrapper package was introduced, `freemarker.ext.dom`. For new usage, we encourage you to use that. It is documented in the part .

The class `freemarker.ext.xml.NodeListModel` provides a template model for wrapping XML documents represented as node trees. Every node list can contain zero or more XML nodes (documents, elements, texts, processing instructions, comments, entity references, CDATA sections, etc.). The node list implements the following template model interfaces with the following semantics:

##### TemplateScalarModel

When used as a scalar, the node list will render the XML fragment that represents its contained nodes. This makes it handy for use in XML-to-XML transforming templates.

##### TemplateCollectionModel

When used as a collection with `list` directive, it will simply enumerate its nodes. Every node will be returned as a new node list consisting of a single node.

##### TemplateSequenceModel

When used as a sequence, it will return the i-th node as a new node list consisting of the single requested node. I.e. to return the 3rd `<chapter>` element of the `<book>` element, you'd use the following (note indexes are zero-based):

    <#assign 3rdChapter = xmldoc.book.chapter[2]>

##### TemplateHashModel

When used as a hash, it is basically used to traverse children. That is, if you have a node list named `book` that wraps an element node with several chapters, then the `book.chapter` will yield a node list with all chapter elements of that book element. The at sign is used to refer to attributes: `book.@title` yields a node list with a single attribute node, that is the title attribute of the book element.

It is important to realize the consequence that, for example, if `book` has no `chapter`-s then `book.chapter` is an empty sequence, so `xmldoc.book.chapter??` will not be `false`, it will be always `true`! Similarly, `xmldoc.book.somethingTotallyNonsense??` will not be `false` either. To check if there was no children found, use `xmldoc.book.chapter?size == 0`.

The hash defines several "magic keys" as well. All these keys start with an underscore. The most notable is the `_text` key which retrieves the text of the node: `${book.@title._text}` will render the value of the attribute into the template. Similarly, `_name` will retrieve the name of the element or attribute. `*` or `_allChildren` returns all direct children elements of all elements in the node list, while `@*` or `_allAttributes` returns all attributes of the elements in the node list. There are many more such keys; here's a detailed summary of all the hash keys:

Key name | Evaluates to
--- | ---
`*` or `_children` | all direct element children of current nodes (non-recursive). Applicable to element and document nodes.
`@*` or `_attributes` | all attributes of current nodes. Applicable to elements only.
`@attributeName` | named attributes of current nodes. Applicable to elements, doctypes and processing instructions. On doctypes it supports attributes `publicId`, `systemId` and `elementName`. On processing instructions, it supports attributes `target` and `data`, as well as any other attribute name specified in data as `name="value"` pair. The attribute nodes for doctype and processing instruction are synthetic, and as such have no parent. Note, however that `@*` does NOT operate on doctypes or processing instructions.
`_ancestor` | all ancestors up to root element (recursive) of current nodes. Applicable to same node types as `_parent`.
`_ancestorOrSelf` | all ancestors of current nodes plus current nodes. Applicable to same node types as `_parent`.
`_cname` | the canonical names of current nodes (namespace URI + local name), one string per node (non-recursive). Applicable to elements and attributes
`_content` | the complete content of current nodes, including children elements, text, entity references, and processing instructions (non-recursive). Applicable to elements and documents.
`_descendant` | all recursive descendant element children of current nodes. Applicable to document and element nodes.
`_descendantOrSelf` | all recursive descendant element children of current nodes plus current nodes. Applicable to document and element nodes.
`_document` | all documents the current nodes belong to. Applicable to all nodes except text.
`_doctype` | doctypes of the current nodes. Applicable to document nodes only.
`_filterType` | is a filter-by-type template method model. When called, it will yield a node list that contains only those current nodes whose type matches one of types passed as argument. You should pass arbitrary number of strings to this method containing the names of types to keep. Valid type names are: "attribute", "cdata", "comment", "document", "documentType", "element", "entity", "entityReference", "processingInstruction", "text".
`_name` | the names of current nodes, one string per node (non-recursive). Applicable to elements and attributes (returns their local names), entities, processing instructions (returns its target), doctypes (returns its public ID)
`_nsprefix` | the namespace prefixes of current nodes, one string per node (non-recursive). Applicable to elements and attributes
`_nsuri` | the namespace URIs of current nodes, one string per node (non-recursive). Applicable to elements and attributes
`_parent` | parent elements of current nodes. Applicable to element, attribute, comment, entity, processing instruction.
`_qname` | the qualified names of current nodes in `[namespacePrefix:]localName` form, one string per node (non-recursive). Applicable to elements and attributes
`_registerNamespace(prefix, uri)` | register a XML namespace with the specified prefix and URI for the current node list and all node lists that are derived from the current node list. After registering, you can use the `nodelist["prefix:localname"]` or `nodelist["@prefix:localname"]` syntaxes to reach elements and attributes whose names are namespace-scoped. Note that the namespace prefix need not match the actual prefix used by the XML document itself since namespaces are compared solely by their URI.
`_text` | the text of current nodes, one string per node (non-recursive). Applicable to elements, attributes, comments, processing instructions (returns its data) and CDATA sections. The reserved XML characters ('<' and '&') are not escaped.
`_type` | Returns a node list containing one string per node describing the type of the node. Possible node type names are: "attribute", "cdata", "comment", "document", "documentType", "element", "entity", "entityReference", "processingInstruction", "text". If the type of the node is unknown, returns "unknown".
`_unique` | a copy of the current nodes that keeps only the first occurrence of every node, eliminating duplicates. Duplicates can occur in the node list by applying uptree-traversals `_parent`, `_ancestor`, `_ancestorOrSelf`, and `_document`. I.e. `foo._children._parent` will return a node list that has duplicates of nodes in foo - each node will have the number of occurrences equal to the number of its children. In these cases, use `foo._children._parent._unique` to eliminate duplicates. Applicable to all node types.
any other key | element children of current nodes with name matching the key. This allows for convenience child traversal in `book.chapter.title` style syntax. Note that `nodeset.childname` is technically equivalent to `nodeset("childname")`, but is both shorter to write and evaluates faster. Applicable to document and element nodes.

##### TemplateMethodModel

When used as a method model, it returns a node list that is the result of evaluating an XPath expression on the current contents of the node list. For this feature to work, you must have the `Jaxen` library in your classpath. For example:

    <#assign firstChapter=xmldoc("//chapter[first()]")>

##### Namespace handling

For purposes of traversal of children elements that have namespace-scoped names, you can register namespace prefixes with the node list. You can do it either in Java, calling the

    public void registerNamespace(String prefix, String uri);

method, or inside a template using the

    ${nodelist._registerNamespace(prefix, uri)}

syntax. From there on, you can refer to children elements in the namespace denoted by the particular URI through the syntax

    nodelist["prefix:localName"]

and

    nodelist["@prefix:localName"]

as well as use these namespace prefixes in XPath expressions. Namespaces registered with a node list are propagated to all node lists that are derived from the original node list. Note also that namespaces are matched by their URI only, so you can safely use a prefix for a namespace inside your template that differs from the prefix in the actual XML document - a prefix is just a local alias for the URI both in the template and in the XML document.

#### Using FreeMarker with Ant

There are two ``FreeMarker Ant tasks'' that we know about:

- `FreemarkerXmlTask`: It comes with the FreeMarker distribution, packed into the `freemarker.jar`. This is a lightweight, easy-to-use Ant task for transforming XML documents with FreeMarker templates. Its approach is that the source files (input files) are XML files, which are rendered to corresponding output files, by a single template. That is, for each XML file, the template will be executed (with the XML document in the data-model), and the template output will be written into a file of similar name than the name of the XML file. Thus, the template file plays a similar role as an XSLT style sheet, but it is FTL, not XSLT.

- FMPP: It's a more heavyweight, less XML centric, third party Ant task (and standalone command-line tool). Its primary approach is that the source files (input files) are template files that generate the corresponding output files themselves, but it also supports the approach of `FreemarkerXmlTask` for the source files that are XML-s. Also, it has extra features over the `FreemarkerXmlTask`. What's its drawback then? As it is more complex and more generalized, it's harder to learn and use it.

  command-line

This section introduces the `FreemarkerXmlTask`. For more information about FMPP visit its homepage: http://fmpp.sourceforge.net/.

In order to use the `FreemarkerXmlTask`, you must first define the `freemarker.ext.ant.FreemarkerXmlTask` inside your Ant buildfile, then call the task. Suppose you want to transform several XML documents to HTML using the hypothetical "xml2html.ftl" template, with XML documents being located in the directory "xml" and HTML documents generated into directory "html". You would write something like:

    <taskdef name="freemarker" classname="freemarker.ext.ant.FreemarkerXmlTask">
      <classpath>
        <pathelement location="freemarker.jar" />
      </classpath>
    </taskdef>
    <mkdir dir="html" />
    <freemarker basedir="xml" destdir="html" includes="**/*.xml" template="xml2html.ftl" />

The task would invoke the template for every XML document. Every document would be parsed into a DOM tree, then wrapped as a FreeMarker node variable. When template processing begins, the special variable, `.node`, is set to the root node of the XML document.

Note that if you are using the legacy (FreeMarker 2.2.x and earlier) XML adapter implementation, that still works, and the root of the XML tree is placed in the data-model as the variable `document`. That contains an instance of the legacy `freemarker.ext.xml.NodeListModel` class.

Note that all properties defined by the build file would be made available as a hash model named "properties". Several other models are made available; for detailed description of what variables are made available to templates as well as what other attributes can the task accept, see the JavaDoc for `freemarker.ext.ant.FreemarkerXmlTask`.

ant task

#### Jython wrapper

The `freemarker.ext.jython` package consists of models that enable any Jython object to be used as a `TemplateModel`. In the very basic case, you only need to call the

    public TemplateModel wrap(Object obj);

method of the `freemarker.ext.jython.JythonWrapper` class. This method will wrap the passed object into an appropriate `TemplateModel`. Below is a summary of the properties of returned model wrappers. Let's assume that the model that resulted from the `JythonWrapper` call on object `obj` is named `model` in the template model root for the sake of the following discussion.

##### TemplateHashModel functionality

`PyDictionary` and `PyStringMap` will be wrapped into a hash model. Key lookups are mapped to the `__finditem__` method; if an item is not found, a model for `None` is returned.

##### TemplateScalarModel functionality

Every python object will implement `TemplateScalarModel` whose `getAsString()` method simply delegates to `toString()`.

##### TemplateBooleanModel functionality

Every python object will implement `TemplateBooleanModel` whose `getAsBoolean()` method simply delegates to `__nonzero__()` in accordance with Python semantics of true/false.

##### TemplateNumberModel functionality

Model wrappers for `PyInteger`, `PyLong`, and `PyFloat` objects implement `TemplateNumberModel` whose `getAsNumber()` method returns `__tojava__(java.lang.Number.class)`.

##### TemplateSequenceModel functionality

Model wrappers for all classes that extend `PySequence` will implement `TemplateSequenceModel` and thus their elements will be accessible by index using the `model[i]` syntax, which will delegate to `__finditem__(i)`. You can also query the length of the array or the size of the list using the `model?size` built-in, which will delegate to `__len__()`.

wrapping jython
jython wrapping

## XML Processing Guide

### Preface

Although FreeMarker was originally designed as a web page template engine, as of version 2.3 it also targets another application domain: transforming XML into arbitrary textual output (e.g. HTML files). Thus, in many cases, FreeMarker is an XSLT alternative.

Technically, there is nothing special in transforming XML documents. It's just like when you do anything else with FreeMarker: you drop the XML document into the data-model (and possibly other variables), and then you merge the data-model with the FTL template(s) that generate the output text. The extra features introduced for better XML processing are the node FTL variable type (symbolizes a node in generic tree structures, usable not only for XML) and the built-ins and directives dealing with them, and the XML wrapper you get out-of-the-box that exposes XML documents as FTL variables for the templates.

What's the difference between using FreeMarker or XSLT? The FTL language has the usual imperative/procedural logic. On the other hand, XSLT is a language with declarative style, designed by "too clever" people, so it's not easy to adopt its logic, nor to use it in many cases. Also its syntax is terribly verbose. However, XSLT's "apply-templates" method can be very handy when you process XML documents, thus FreeMarker supports something similar called the ``visitor pattern''. So in many applications, it is much easier to write FTL stylesheets than XSLT style-sheets. Another fundamental difference is that FTL "transforms" the node tree to text, while XSLT transforms the tree to another tree. So you cannot always use FreeMarker where you can use XSLT.

### Exposing XML documents

#### The DOM tree

We will use this XML document for the examples:

    <book>
      <title>Test Book</title>
      <chapter>
        <title>Ch1</title>
        <para>p1.1</para>
        <para>p1.2</para>
        <para>p1.3</para>
      </chapter>
      <chapter>
        <title>Ch2</title>
        <para>p2.1</para>
        <para>p2.2</para>
      </chapter>
    </book>

W3C DOM models an XML document as a tree of nodes. The node tree of the above XML can be visualized as:

    document
     |
     +- element book
         |
         +- text "\n  "
         |
         +- element title
         |   |
         |   +- text "Test Book"
         |
         +- text "\n  "
         |
         +- element chapter
         |   |
         |   +- text "\n    "
         |   |
         |   +- element title
         |   |   |
         |   |   +- text "Ch1"
         |   |
         |   +- text "\n    "
         |   |
         |   +- element para
         |   |   |
         |   |   +- text "p1.1"
         |   |
         |   +- text "\n    "
         |   |
         |   +- element para
         |   |   |
         |   |   +- text "p1.2"
         |   |
         |   +- text "\n    "
         |   |
         |   +- element para
         |      |
         |      +- text "p1.3"
         |
         +- element
             |
             +- text "\n    "
             |
             +- element title
             |   |
             |   +- text "Ch2"
             |
             +- text "\n    "
             |
             +- element para
             |   |
             |   +- text "p2.1"
             |
             +- text "\n    "
             |
             +- element para
                 |
                 +- text "p2.2"

Note that the disturbing `"\n "`-s are the line-breaks (indicated here with `\n`, an escape sequence used in FTL string literals) and the indentation spaces between the tags.

Notes on the DOM related terminology:

- The topmost node of a tree is called the root. In the case of XML documents, it is always the ``document'' node, and not the top-most element (`book` in this example).

- We say that node B is the child of node A, if B is the immediate descendant of A. For example, the two `chapter` element nodes are the children of the `book` element node, but the `para` element nodes are not.

- We say that node A is the parent of node B, if A is the immediate ascendant of node B, that is, if B is the children of A. For example, the `book` element node is the parent of the two `chapter` element nodes, but it is not the parent of the `para` element nodes.

- There are several kind of components that can occur in XML documents, such as elements, text, comments, processing instructions, etc. All such components are nodes in the DOM tree, so there are element nodes, text nodes, comment nodes, etc. In principle, the attributes of elements are also nodes in the tree -- they are the children of the element --, but still, usually we (and other XML related technologies) exclude them of element children. So basically they don't count as children nodes.

The programmer drops the document node of the DOM tree into the FreeMarker data-model, and then the template author can walk the DOM tree using that variable as the starting-point.

The DOM nodes in FTL correspond to node variables. This is a variable type, similarly to type string, number, hash, etc. Node variable type makes it possible for FreeMarker to get the parent node and the child nodes of a node. This is technically required to allow the template author to navigate between the nodes, say, to use the node built-ins or the `visit` and `recurse` directives; we will show the usage of these in the further chapters.

#### Putting the XML into the data-model

This section is for programmers.

It's easy to create a simple program to try the examples. Just replace the ``Create a data-model'' part of the example of Programmer's Guide Quickstart with this:

    /* Create a data-model */
    Map root = new HashMap();
    root.put(
            "doc",
            freemarker.ext.dom.NodeModel.parse(new File("the/path/of/the.xml")));

and then you have a program that outputs the result of the XML transformation to the standard output (usually the terminal screen).

Notes:

- The `parse` method removes comment and processing instruction nodes by default. See the API for more details.

- `NodeModel` also allows you to wrap `org.w3c.dom.Node`-s directly. You may want to clean up the DOM tree first with the static utility methods, such as `NodeModel.simplify` or your own custom cleanup routines.

Note that there are tools available that you can use to generate files from XML documents, so you don't have to write your own for this common task. See here...

XML exposing

### Imperative XML processing

#### Learning by example

This section uses the DOM tree and the variable made in the previous chapter.

Assume that the programmer has put the XML document into the data-model as variable `doc`. This variable corresponds to the root of the DOM tree, the ``document''. The actual variable structure behind `doc` is wily enough, and only roughly resembles the DOM tree. So instead of getting lost in the details, let's see how to use it by example.

##### Accessing elements by name

This FTL prints the title of the book:

    <h1>${doc.book.title}</h1>

The output will be:

    <h1>Test Book</h1>

As you see, both `doc` and `book` can be used as hashes; you get their child nodes as subvariables. Basically, you describe the path by which you reach the target (element `title`) in the DOM tree. You may notice that there was some swindle above: with `${doc.book.title}`, it seems that we instruct FreeMarker to print the `title` element itself, but we should print its child text node (check the DOM tree). It still works, because elements are not only hash variables, but string variables as well. The scalar value of an element node is the string resulting from the concatenation of all its text child nodes. However, trying to use an element as scalar will cause error if the element has child elements. For example `${doc.book}` would stop with error.

This FTL prints the titles of the two chapters:

    <h2>${doc.book.chapter[0].title}</h2>
    <h2>${doc.book.chapter[1].title}</h2>

Here, as `book` has 2 `chapter` element children, `doc.book.chapter` is a sequence that stores the two element nodes. Thus, we can generalize the above FTL, so it works with any number of chapters:

    <#list doc.book.chapter as ch>
      <h2>${ch.title}</h2>
    </#list>

But what's if there is only one chapter? Actually, when you access an element as hash subvariable, it is always a sequence as well (not only hash and string), but if the sequence contains exactly 1 item, then the variable also acts as that item itself. So, returning to the first example, this would print the book title as well:

    <h1>${doc.book[0].title[0]}</h1>

But you know that there is exactly 1 `book` element, and that a book has exactly 1 title, so you can omit the `[0]`-s. `${doc.book.chapter.title}` would work too, if the book happen to have only 1 `chapter`-s (otherwise it is ambiguous: how is it to know if the `title` of which `chapter` you want? So it stops with an error.). But since a book can have multiple chapters, you don't use this form. If the element `book` has no `chapter` child, then `doc.book.chapter` will be a 0 length sequence, so the FTL with `<#list ...>` will still work.

It is important to realize the consequence that, for example, if `book` has no `chapter`-s then `book.chapter` is an empty sequence, so `doc.book.chapter??` will not be `false`, it will be always `true`! Similarly, `doc.book.somethingTotallyNonsense??` will not be `false` either. To check if there was no children found, use `doc.book.chapter[0]??` (or `doc.book.chapter?size == 0`). Of course you can use similarly all the missing value handler operators (e.g. `doc.book.author[0]!"Anonymous"`), just don't forget that `[0]`.

The rule with sequences of size 1 is a convenience feature of the XML wrapper (implemented via multi-type FTL variables). It will not work with other sequences in general.

Now we finish the example by printing all the `para`-s of each chapter:

    <h1>${doc.book.title}</h1>
    <#list doc.book.chapter as ch>
      <h2>${ch.title}</h2>
      <#list ch.para as p>
        <p>${p}
      </#list>
    </#list>

this will print:

    <h1>Test</h1>
      <h2>Ch1</h2>
        <p>p1.1
        <p>p1.2
        <p>p1.3
      <h2>Ch2</h2>
        <p>p2.1
        <p>p2.2

The above FTL could be written more nicely as:

    <#assign book = doc.book>
    <h1>${book.title}</h1>
    <#list book.chapter as ch>
      <h2>${ch.title}</h2>
      <#list ch.para as p>
        <p>${p}
      </#list>
    </#list>

Finally, a ``generalized`` usage of the child selector mechanism: this template lists all `para`-s of the example XML document:

    <#list doc.book.chapter.para as p>
      <p>${p}
    </#list>

The output will be:

      <p>p1.1
      <p>p1.2
      <p>p1.3
      <p>p2.1
      <p>p2.2

This example shows that hash subvariables select the children of a sequence of notes (just in the earlier examples that sequence happened to be of size 1). In this concrete case, subvariable `chapter` returns a sequence of size 2 (since there are two `chapter`-s), and then subvariable `para` selects the `para` child nodes of all nodes in that sequence.

A negative consequence of this mechanism is that things like `doc.somethingNonsense.otherNonsesne.totalNonsense` will just evaluate to an empty sequence, and you don't get any error messages.

##### Accessing attributes

This XML is the same as the original, except that it uses attributes for the titles, instead of elements:

    <!-- THIS XML IS USED FOR THE "Accessing attributes" CHAPTER ONLY! -->
    <!-- Outside this chapter examples use the XML from earlier.       -->

    <book title="Test">
      <chapter title="Ch1">
        <para>p1.1</para>
        <para>p1.2</para>
        <para>p1.3</para>
      </chapter>
      <chapter title="Ch2">
        <para>p2.1</para>
        <para>p2.2</para>
      </chapter>
    </book>

The attributes of an element can be accessed in the same way as the child elements of the element, except that you put an at-sign (@) before the name of the attribute:

    <#assign book = doc.book>
    <h1>${book.@title}</h1>
    <#list book.chapter as ch>
      <h2>${ch.@title}</h2>
      <#list ch.para as p>
        <p>${p}
      </#list>
    </#list>

This will print exactly the same as the previous example.

Getting attributes follows the same logic as getting child elements, so the result of `ch.@title` above is a sequence of size 1. If there were no `title` attribute, then the result would be a sequence of size 0. So be ware, using existence built-ins is tricky here too: if you are curious if `foo` has attribute `bar` then you have to write `foo.@bar[0]??`. (`foo.@bar??` is wrong, because it always returns `true`.) Similarly, if you want a default value for the `bar` attribute, then you have to write `foo.@bar[0]!"theDefaultValue"`.

As with child elements, you can select the attributes of multiple nodes. For example, this template prints the titles of all chapters:

    <#list doc.book.chapter.@title as t>
      ${t}
    </#list>

##### Exploring the tree

This FTL will enumerate all child nodes of the book element:

    <#list doc.book?children as c>
    - ${c?node_type} <#if c?node_type = 'element'>${c?node_name}</#if>
    </#list>

this will print:

    - text
    - element title
    - text
    - element chapter
    - text
    - element chapter
    - text

The meaning of `?node_type` is probably clear without explanation. There are several node types that can occur in a DOM tree, such as `"element"`, `"text"`, `"comment"`, `"pi"`, ...etc.

The `?node_name` returns the name of element for element nodes. For other node types, it also returns something, but that's mainly useful for declarative XML processing, which will be discussed in a later chapter.

If the book element had attributes, they would not appear in the above list, for practical reasons. But you can get a list that contains all attributes of the element, with subvariable `@@` of the element variable. If you modify the first line of the XML to this:

    <book foo="Foo" bar="Bar" baaz="Baaz">

and run this FTL:

    <#list doc.book.@@ as attr>
    - ${attr?node_name} = ${attr}
    </#list>

then you get this output (or something similar):

    - baaz = Baaz
    - bar = Bar
    - foo = Foo

Returning to the listing of children, there is a convenience subvariable to list only the element children of an element:

    <#list doc.book.* as c>
    - ${c?node_name}
    </#list>

This will print:

    - title
    - chapter
    - chapter

You get the parent of an element with the `parent` built-in:

    <#assign e = doc.book.chapter[0].para[0]>
    <#-- Now e is the first para of the first chapter -->
    ${e?node_name}
    ${e?parent?node_name}
    ${e?parent?parent?node_name}
    ${e?parent?parent?parent?node_name}

This will print:

    para
    chapter
    book
    @document

In the last line you have reached the root of the DOM tree, the document node. It's not an element, and this is why it has that strange name; don't deal with it now. Obviously, the document node has no parent.

You can quickly go back to the document node using the `root` built-in:

    <#assign e = doc.book.chapter[0].para[0]>
    ${e?root?node_name}
    ${e?root.book.title}

This will print:

    @document
    Test Book

For the complete list of built-ins you can use to navigate in the DOM tree, read the reference of node built-ins.

##### Using XPath expressions

XPath expressions work only if Jaxen (recommended, but use at least Jaxen 1.1-beta-8, not older) or Apache Xalan classes are available. (Apache Xalan classes are included in Sun J2SE 1.4, 1.5 and 1.6 (and maybe later too); no separate Xalan jar is needed.)

If a hash key used with a node variable can't be interpreted otherwise (see the next section for the precise definition), then it will by interpreted as an XPath expression. For more information on XPath, please visit http://www.w3.org/TR/xpath.

For example, here we list the `para` elements of the chapter with title ``Ch1'':

    <#list doc["book/chapter[title='Ch1']/para"] as p>
      <p>${p}
    </#list>

It will print:

      <p>p1.1
      <p>p1.2
      <p>p1.3

The rule with sequences of length 1 (explained in earlier sections) stands for XPath results as well. That is, if the resulting sequence contains exactly 1 node, it also acts as the node itself. For example, print the first paragraph of chapter ``Ch1'':

    ${doc["book/chapter[title='Ch1']/para[1]"]}

which prints the same as:

    ${doc["book/chapter[title='Ch1']/para[1]"][0]}

The context node of the XPath expression is the node (or sequence of nodes) whose hash subvariable is used to issue the XPath expression. Thus, this prints the same as the previous example:

    ${doc.book["chapter[title='Ch1']/para[1]"]}

Note that currently you can use a sequence of 0 or multiple (more than 1) nodes as context only if the programmer has set up FreeMarker to use Jaxen instead of Xalan.

Also note that XPath indexes sequence items from 1, while FTL indexes sequence items from 0. Thus, to select the first chapter, the XPath expression is `"/book/chapter[1]"`, while the FTL expression is `book.chapter[0]`.

If the programmer has set up FreeMarker to use Jaxen instead of Xalan, then FreeMarker variables are visible with XPath variable references:

    <#assign currentTitle = "Ch1">
    <#list doc["book/chapter[title=$currentTitle]/para"] as p>
    ...

Note that `$currentTitle` is not a FreeMarker interpolation, as there are no `{` and `}` there. That's an XPath expression.

The result of some XPath expressions is not a node-set, but a string, a number, or a boolean. For those XPath expressions, the result is an FTL string, number, or boolean variable respectively. For example, the following will count the total number of `para` elements in the XML document, so the result is a number:

    ${x["count(//para)"]}

The output will be:

    5

##### XML namespaces

Be default, when you write something like `doc.book`, then it will select the element with name `book` that does not belongs to any XML namespace (similarly to XPath). If you want to select an element that is inside an XML namespace, you must register a prefix and use that. For example, if element `book` is in XML namespace `http://example.com/ebook`, then you have to associate a prefix with it at the top of the template with the `ns_prefixes` parameter of the `ftl` directive:

    <#ftl ns_prefixes={"e":"http://example.com/ebook"}>

And now you can write expressions as `doc["e:book"]`. (The usage of square bracket syntax was required because the colon would confuse FreeMarker otherwise.)

As the value of `ns_prefixes` is a hash, you can register multiple prefixes:

    <#ftl ns_prefixes={
        "e":"http://example.com/ebook",
        "f":"http://example.com/form",
        "vg":"http://example.com/vectorGraphics"}
    >

The `ns_prefixes` parameter affects the whole FTL namespace. This means in practice that the prefixes you have registered in the main page template will be visible in all `<#include ...>`-d templates, but not in `<#imported ...>`-d templates (often referred as FTL libraries). Or from another point of view, an FTL library can register XML namespace prefixes for it's own use, without interfering with the prefix registrations of the main template and other libraries.

Note that, if an input document is dominated by a given XML namespace, you can set that as the default namespace for convenience. This means that if you don't use prefix, as in `doc.book`, then it selects element that belongs to the default namespace. The setting of the default namespace happens with reserved prefix `D`, for example:

    <#ftl ns_prefixes={"D":"http://example.com/ebook"}>

Now expression `doc.book` select the `book` element that belongs to XML namespace `http://example.com/ebook`. Unfortunately, XPath does not support this idea of a default namespace. Thus, in XPath expressions, element names without prefixes always select the elements that does not belong to any XML namespace. However, to access elements in the default namespace you can directly use prefix `D`, for example: `doc["D:book/D:chapter[title='Ch1']"]`.

Note that when you use a default namespace, then you can select elements that does not belong to any node namespace with reserved prefix `N`, for example `doc.book["N:foo"]`. It doesn't go for XPath expressions, where the above can be witten as `doc["D:book/foo"]`.

XML namespace in imperative processing

##### Don't forget escaping!

We have made a big mistake in all examples. We generate output of HTML format, and HTML format reserves characters as `<`, `&`, etc. So when we print plain text (as the titles and paragraphs), we have to escape it. Thus, the correct version of the example is:

    <#escape x as x?html>
    <#assign book = doc.book>
    <h1>${book.title}</h1>
    <#list book.chapter as ch>
      <h2>${ch.title}</h2>
      <#list ch.para as p>
        <p>${p}
      </#list>
    </#list>
    </#escape>

So if the book title is "Romeo & Julia", the resulting HTML output will be correctly:

    ...
    <h1>Romeo &amp; Julia</h1>
    ...

#### Formal description

Every variable that corresponds to a single node in the DOM tree is a multi-type variable of type node and type hash (for programmers: implements both `TemplateNodeModel` and `TemplateHashModel`). Thus, you can use the node built-ins with them. Hash keys are interpreted as XPath expressions, except the special keys shown in the table below. Some of the node variables also have string type, so you can use them as string variables (for programmers: they implement `TemplateScalarModel`).

Node type (`?node_type`) | Node name (`?node_name`) | String value (e.g. `<p>${node}`) | Special hash keys
--- | --- | --- | ---
`"document"` | `"@document"` | No string value. (Error when you try to use it as string.) | `"elementName"`, `"prefix:elementName"`, `"*"`, `"**"`, `"@@markup"`, `"@@nested_markup"`, `"@@text"`
`"element"` | `"name"`: the name of the element. This is the local name (i.e. name without namespace prefix). | If it has no element children, the text of all text node children concatenated together. Error otherwise, when you try to use it as string. | `"elementName"`, `"prefix:elementName"`, `"*"`, `"**"`, `"@attrName"`, `"@prefix:attrName"`, `"@@"`, `"@*"`, `"@@start_tag"`, `"@@end_tag"`, `"@@attributes_markup"`, `"@@markup"`, `"@@nested_markup"`, `"@@text"`, `"@@qname"`
`"text"` | `"@text"` | The text itself. | `"@@markup"`, `"@@nested_markup"`, `"@@text"`
`"pi"` | `"@pi$target"` | The part between the target name and the `?>`. | `"@@markup"`, `"@@nested_markup"`, `"@@text"`
`"comment"` | `"@comment"` | The text of the comment, without the delimiters `<!--` and `-->`. | `"@@markup"`, `"@@nested_markup"`, `"@@text"`
`"attribute"` | `"name"`: the name of the attribute. This is the local name (i.e. name without namespace prefix). | The value of the attribute. | `"@@markup"`, `"@@nested_markup"`, `"@@text"`, `"@@qname"`
`"document_type"` | `"@document_type$name"`: `name` is the name of the document element. | No string value. (Error when you try to use it as string.) | `"@@markup"`, `"@@nested_markup"`, `"@@text"`

Notes:

- There is no CDATA type. CDATA nodes are transparently considered as text nodes.

- Variables do not support `?keys` and `?values`.

- Element and attribute node names are local names, that is, they do not contain the namespace prefix. The URI of the namespace the node belongs to can be queried with the `?node_namespace` built-in.

- XPath expression needs Jaxen (recommended, but please use 1.1-beta-8 or later; download it here) or Apache Xalan classes available, or an error will stop template execution. Note, however, that as some special hash keys hide the XPath expressions of the same meaning, those XPath expressions will work even if there is no XPath implementation available. If both Xalan and Jaxen is available, FreeMarker will use Xalan, unless you choose Jaxen by calling `freemarker.ext.dom.NodeModel.useJaxenXPathSupport()` from Java.

- If Jaxen is used for the XPath support (not Xalan), then FreeMarker variables are visible with XPath variable references (e.g. `doc["book/chapter[title=$currentTitle]"]`).

Meaning of special hash keys:

- `"elementName"`, `"prefix:elementName"`: Returns the sequence of child nodes that are elements of name `elementName`. (Note that the term ``child'' means immediate descendant.) The selection is XML name-space aware, unless the XML document was persed with an XML parser that was not in namespace aware mode. In XML name-space aware mode, names without prefix (elementName) selects only elements that doesn't belong to any XML name-space (unless you have registered a default XML namespace), and names with prefix (prefix:elementName) selects only elements that are belonging to the XML namespace denoted by the prefix. The registration of prefixes and the setting of the default XML namespace is done with the `ns_prefixes` parameter of the `ftl` directive.

- `"*"`: Returns the sequence of all child (direct descedant) element nodes. The sequence will contain the elements in the ``document order'', that is, in the order in which the first character of the XML representation of each node occurs (after expansion of general entities).

- `"**"`: Returns the sequence of all descendant element nodes. The sequence will contain the elements in the document order.

- `"@attName"`, `"@prefix:attrName"`: Returns the attribute `attName` of the element as a sequence of size 1 that contains the attribute node, or as an empty sequence if the attribute does not exist (so to check if an attribute exists use `foo.@attName[0]??`, not `foo.@attName??`). As with special key `"elementName"`, if the length of the sequence is 1, then it also acts as its first subvariable. If no `prefix` is used, then it returns only attribute that does not use XML namespace (even if you have set a default XML namespace). If a `prefix` is used, it returns only the attribute that belongs to the XML namespace associated with the `prefix`. The registration of prefixes is done with the `ns_prefixes` parameter of the `ftl` directive.

- `"@@"` or `"@*"`: Returns the sequence of attribute nodes belonging to the parent element. This is the same as XPath `@*`.

- `"@@qname"`: Returns the full-qualified name of the element (such as `e:book`, in contrast to the local name returned by `?node_name` that is `book`) . The prefix used (as `e`) is chosen based on the prefix registered in the current namespace with the `ns_prefixes` parameter of the `ftl` directive, and not influenced by the prefix used in the source XML document. If you have set a default XML namespace, then for nodes that use that, prefix `D` will be used. For nodes that does not belong to an XML namespace, no prefix is used (even if you have set a default namespace). If there is no prefix registered for the namespace of the node, the result is a non-existent variable (`node.@@qname??` is `false`).

- `"@@markup"`: This returns the full XML markup of a node, as a string. (Full XML markup means that it also contains the markup of the child nodes, and the markup of the children of the child nodes, and so on.) The markup you get is not necessary the same as the markup in the source XML file, it's just semantically identical. Especially, note that CDATA sections will become to plain text. Also note that depending on how did you wrapped the original XML document with FreeMarker, comment or processing instruction nodes may were removed, and then they will be missing from the output of course. The first outputted start tag will contain `xmlns:prefix` attributes for each XML name-spaces used in the outputted XML fragment, and those prefixes will be used in the outputted element and attribute names. These prefixes will be the same as the prefixes registered with the `ns_prefixes` parameter of the `ftl` directive (no prefix will be used for `D`, as it will be registered as the default name-space with an `xmlns` attribute), or if no prefix was assigned for a XML name-space with that, then an arbitrary chosen unused prefix is used.

- `"@@nested_markup"`: This is similar to `"@@markup"`, but it returns the XML markup of an element without its opening and closing tags. For the document node, it returns the same as `"@@markup"`. For other node types (text, processing instruction, etc.), it returns an empty string. Unlike with `"@@markup"`, no `xmlns:prefix` attributes will be placed into the ouput, but regarding the prefixes used in element and attribute names the rules are the same.

- `"@@text"`: This returns the value of all text nodes that occur within the node (all descendant text nodes, not just direct children), concatenated together into a single string. If the node has no text node children, then the result is an empty string.

- `"@@start_tag"`: Returns the markup of the start-tag of the element node. As with `@@markup`, the output is not necessary the same as in the original XML document, but it is semantically equivalent with that. Regarding the XML name-spaces (`xmlns:prefix` attributes in the output, etc.) the rules are the same as with `"@@markup"`

- `"@@end_tag"`: Returns the markup of the end-tag of the element node. As with `@@markup`, the output is not necessary the same as in the original XML document, but it is semantically equivalent with that.

- `@@attributes_markup`: Returns the markup of the attributes of the element node. As with `@@markup`, the output is not necessary the same as in the original XML document, but it is semantically equivalent with that.

##### Node sequences

Many of the special hash keys (indicated in the above list), and XPath expressions that result in node-sets (see the XPath recommendation) return a sequence of nodes.

These node sequences, if they store exactly 1 subvariable, will also act as the subvariable itself. For example, `${book.title[0]}` will do the same as `${book.title}`, if there is only one `title` element child of element `book`.

Returning an empty node sequence is a normal situation. For example, if in a concrete XML document, element `book` has no child element `chapter`, then `book.chapter` results in an empty node sequence. Beware! This also means, that `book.chaptre` (note the typo) will also return empty node sequence, and will not stop with error. Also, `book.chaptre??` (note the typo) will return `true` because the empty sequence exists, so you have to use `book.chaptre[0]??` for the check.

Node sequences that store not 1 nodes (but 0 or more than 1 nodes) also support some of the hash keys described above. Namely, the following special keys are supported:

- `"elementName"`, `"prefix:elementName"`

- `"@attrName"`, `"@prefix:attrName"`

- `"@@markup"`, `"@@nested_markup"`

- `"@@text"`

- `"*"`, `"**"`

- `"@@"`, `"@*"`

When you apply one of the above special keys on a node sequence that contains more than 1 or 0 nodes, then for each node in the sequence (where the special key does make sense, e.g. text nodes will be skipped for key `*` or `@foo`), the special key will be applied as it was explained for single nodes, and the results will be concatenated to form the final result. The results will be concatenated in the order as the corresponding nodes occur in the node sequence. The concatenation means string or sequence concatenation depending on the type of the results. If the special key would result in a string for a single node, then for multiple nodes the result is a single string too (the results for the single nodes concatenated), and if the special key would return a sequence for a single node, then for multiple nodes the result is a single sequence too. If there are 0 nodes in the sequence you apply the special key on, the string result is an empty string or an empty sequence respectively.

XPath expressions can be used with node sequences. However, for 0 or more than 1 nodes it will work only if you use Jaxen instead of Xalan, because of the limitations of the Xalan XPath implementation.

XML imperative processing

### Declarative XML Processing

#### Basics

This section uses the DOM tree and the variable made in a previous chapter.

With the imperative approach of XML processing -- this was shown in the previous chapter -- you write an FTL program that walks the tree to find the different kind of nodes. With the declarative approach, you rather define how to handle the different kind of nodes, and then let FreeMarker walk the tree an call the handlers you have defined. This approach is useful for complex XML schemas, where the same element can occur as the child of many other elements. Examples of such schemas are XHTML and XDocBook.

The directive you most often use with the declarative approach is the `recurse` directive. This directive gets a node variable as parameter, and ``visits'' all its children nodes, one after the other, starting with the first child. ``Visiting'' a node means that it calls a user-defined directive (like a macro) that has the same name as the name of the child node (`?node_name`). We say on this, that the user-defined directive handles the node. The node that the user-defined directive just handles is available as special variable `.node`. For example, this FTL:

    <#recurse doc>

    <#macro book>
      I'm the book element handler, and the title is: ${.node.title}
    </#macro>

will print (I have removed some disturbing white-space form the output):

    I'm the book element handler, and the title is: Test Book

If you call `recurse` without parameter, then it uses `.node`, that is, it visits all children nodes of the node being handled currently. So this FTL:

    <#recurse doc>

    <#macro book>
      Book element with title ${.node.title}
        <#recurse>
      End book
    </#macro>

    <#macro title>
      Title element
    </#macro>

    <#macro chapter>
      Chapter element with title: ${.node.title}
    </#macro>

will print (I have removed disturbing white-space form the output):

    Book element with title Test Book
    Title element
    Chapter element with title: Ch1
    Chapter element with title: Ch2
    End book

You have seen how to define handlers for element nodes, but not how to define handler for the text nodes. Since the name of the handler is the same as the node-name of nodes it handles, and as the node-name of all text nodes is `@text` (see the table), you define handler for the text nodes like this:

    <#macro @text>${.node?html}</#macro>

Note the `?html`. You have to HTML-escape the text, since you generate output of HTML format.

Here it is the template that transforms the XML to complete HTML:

    <#recurse doc>

    <#macro book>
      <html>
        <head>
          <title><#recurse .node.title></title>
        </head>
        <body>
          <h1><#recurse .node.title></h1>
          <#recurse>
        </body>
      </html>
    </#macro>

    <#macro chapter>
      <h2><#recurse .node.title></h2>
      <#recurse>
    </#macro>

    <#macro para>
      <p><#recurse>
    </#macro>

    <#macro title>
      <#--
        We have handled this element imperatively,
        so we do nothing here.
      -->
    </#macro>

    <#macro @text>${.node?html}</#macro>

and the output will be (now I will honestly include the annoying white-space...):

      <html>
        <head>
          <title>Test Book</title>
        </head>
        <body>
          <h1>Test Book</h1>

        <h2>Ch1</h2>

          <p>p1.1

          <p>p1.2

          <p>p1.3

        <h2>Ch2</h2>

          <p>p2.1

          <p>p2.2

        </body>
      </html>

Note that you can reduce substantially the amount of superfluous whitespace in the output by using the trim directives, as `<#t>`. See also:

You may say that the FTL that did it with imperative approach was much shorter. That's true, but the example XML uses a very simple schema, and as I said, the declarative approach brings its form with XML schemas that are not that firm about what element can occur where. Say, introduce element `mark`, that should color text to red, does not mater where do you use it; in a `title`, or in a `para`. For this, with the declarative approach, you just add a macro:

    <#macro mark><font color=red><#recurse></font></#macro>

And then `<mark>...</mark>` will automatically work everywhere. So for certain XML schemas, declarative XML processing will actually result in shorter, and what is even more important, much clearer FTL-s, than imperative XML processing. It's up to you to decide which approach to use when; don't forget that you can mix the two approaches freely. Say, in an element handler, you can use imperative approach to process the contents of that element.

#### Details

##### Default handlers

For some XML node types, there is a default handler, which will handle the node if you haven't defined a handler for the node (i.e. if there is no user-defined directive available with name identical to the node name). Here are these node types, and what the default handler does:

- Text node: prints the text as it. Note, that in most applications, this will not be good for you, because you should escape the text before you send it to the output (with `?html` or `?xml` or `?rtf`, ...etc. depends on the output format).

- Processing instruction node: call handler called `@pi` if you have created such user-defined directive, otherwise do nothing (ignore the node).

- Comment node, document type node: Do nothing (ignore the node).

- Document node: Call `recurse`, that is, visit all children of the document node.

Element and attribute nodes will be handled according to the usual, XML independent mechanism. That is, `@node_type` will be called as handler, and if that's not defined, then an error stops template processing.

In the case of element nodes, this means that if you define a macro (or other kind of user-defined directive) called `@element`, that will catch all element nodes, which has no more specific handler. If you have no `@element` handler, then you must define a handler for all possible elements.

Attribute nodes are not visited by the `recurse` directive, so you don't need to write handlers for them.

##### Visiting a single node

With the `visit` directive you can visit a single node, instead of the children of the node: `<#visit nodeToVisist>`. This can be useful sometimes.

##### XML namespaces

We said that the name of the handler user-defined directive (like a macro) for an element is the name of the element. In fact, it is the full-qualified name of the element: `prefix:elementName`. The rules regarding the usage of `prefix`-es is the same as with imperative processing. Thus, the user-defined `book` directive handles only element `book` that does not belong to any XML namespace (unless you have specified a default XML namespace). So if the example XML would use XML namespace `http://example.com/ebook`:

    <book xmlns="http://example.com/ebook">
    ...

Then the FTL should look as this:

    <#ftl ns_prefixes={"e":"http://example.com/ebook"}>

    <#recurse doc>

    <#macro "e:book">
      <html>
        <head>
          <title><#recurse .node["e:title"]></title>
        </head>
        <body>
          <h1><#recurse .node["e:title"]></h1>
          <#recurse>
        </body>
      </html>
    </#macro>

    <#macro "e:chapter">
      <h2><#recurse .node["e:title"]></h2>
      <#recurse>
    </#macro>

    <#macro "e:para">
      <p><#recurse>
    </#macro>

    <#macro "e:title">
      <#--
        We have handled this element imperatively,
        so we do nothing here.
      -->
    </#macro>

    <#macro @text>${.node?html}</#macro>

Or, you can define a default XML namespace, and then the further part of the template remains the same as in the original XML namespace free example:

    <#ftl ns_prefixes={"D":"http://example.com/ebook"}>

    <#recurse doc>

    <#macro book>
    ...

But in this case don't forge that in XPath expressions (we didn't used any in the example) the default XML namespace must be accessed with an explicit `D:` since names without prefix always refer to nodes with no XML namespace in XPath. Also note that with the same logic as with imperative XML processing, the name of handlers for elements that has no XML namespace is `N:elementName` if (and only if) there is a default XML namespace. However, for nodes that are not of type element (such as text nodes), you never use the `N` prefix in the handler name, because those nodes are free of the idea of XML namespaces. So for example, the handler for text nodes is always just `@text`.

For more detailed information, please read the reference of `recurse` and `visit` directives.

XML namespaces in declarative processing
XML declarative processing
XSLT

## Reference

### Built-in Reference

#### Alphabetical index

- ancestors

- byte

- c

- cap_first

- capitalize

- ceiling

- children

- chop_linebreak

- chunk

- contains

- date for dates, for strings

- datetime for dates, for strings

- double

- ends_with

- eval

- first

- floor

- groups

- float

- has_content

- html

- index_of

- int

- interpret

- is_...

- iso, iso_...

- j_string

- js_string

- keys

- last

- last_index_of

- left_pad

- length

- long

- lower_case

- matches

- namespace

- new

- node_namespace

- node_name

- node_type

- number

- number_to_date, number_to_datetime, number_to_time

- parent

- replace

- reverse

- right_pad

- round

- root

- rtf

- short

- size

- sort

- seq_contains

- seq_index_of

- seq_last_index_of

- sort_by

- split

- starts_with

- string: for strings, for numbers, for booleans, for date/times

- substring

- time for dates, for strings

- trim

- uncap_first

- upper_case

- url

- values

- word_list

- xhtml

- xml

If you don't find a built-in here that you have seen in a working template, probably you will find it here:

built-in

#### Built-ins for strings

##### substring

This built-in exists since FreeMarker 2.3.7.

Synopsis: `exp?substring(from, toExclusive)`, also callable as `exp?substring(from)`

A substring of the string. `from` is the index of the first character. It must be a number that is at least 0 and less than or equal with `toExclusive`, or else an error will abort the template processing. The `toExclusive` is the index of the character position after the last character of the substring, or with other words, it is one greater than the index of the last character. It must be a number that is at least 0 and less than or equal to the length of the string, or else an error will abort the template processing. If the `toExclusive` is omitted, then it defaults to the length of the string. If a parameter is a number that is not an integer, only the integer part of the number will be used.

Example:

    - ${'abc'?substring(0)}
    - ${'abc'?substring(1)}
    - ${'abc'?substring(2)}
    - ${'abc'?substring(3)}

    - ${'abc'?substring(0, 0)}
    - ${'abc'?substring(0, 1)}
    - ${'abc'?substring(0, 2)}
    - ${'abc'?substring(0, 3)}

    - ${'abc'?substring(0, 1)}
    - ${'abc'?substring(1, 2)}
    - ${'abc'?substring(2, 3)}

The output:

    - abc
    - bc
    - c
    -

    -
    - a
    - ab
    - abc

    - a
    - b
    - c

substring 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 mouse
    GreEN mouse
    - green mouse

In the case of `"- green mouse"`, the first word is the `-`.

cap_first built-in

##### uncap_first

The opposite of `cap_first`. The string with the very first word of the string un-capitalized.

uncap_first built-in

##### 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 Mouse
    Green Mouse

capitalize built-in

##### chop_linebreak

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

chop_linebreak built-in

##### date, time, datetime

The string converted to a date value. It is recommended to specify a parameter that specifies the format. For example:

    <#assign test1 = "10/25/1995"?date("MM/dd/yyyy")>
    <#assign test2 = "15:05:30"?time("HH:mm:ss")>
    <#assign test3 = "1995-10-25 03:05 PM"?datetime("yyyy-MM-dd hh:mm a")>
    ${test1}
    ${test2}
    ${test3}

will print something like (depends on the output locale (language) and on other settings):

    Oct 25, 1995
    3:05:30 PM
    Oct 25, 1995 3:05:00 PM

Note that the dates was converted back to string according to the `date_format`, `time_format` and `datetime_format` settings (for more information about converting dates to strings read: string built-in for dates, date interpolations). It does not mater what format did you use when you have converted the strings to dates.

You don't have to use the format parameter, if you know what the default date/time/datetime format will be when the template is processed:

    <#assign test1 = "Oct 25, 1995"?date>
    <#assign test2 = "3:05:30 PM"?time>
    <#assign test3 = "Oct 25, 1995 03:05:00 PM"?datetime>
    ${test1}
    ${test2}
    ${test3}

If the string is not in the appropriate format, an error will abort template processing when you try to access this built-in.

type-casting
converting between types
date built-in
time built-in
datetime built-in
string to date
string to time
converting string to date
converting string to time
parsing string as date
parsing string as time

##### ends_with

Returns if this string ends with the specified substring. For example `"redhead"?ends_with("head")` returns boolean true. Also, `"head"?ends_with("head")` will return true.

ends_with built-in

##### html

The string as HTML markup. That is, the string with all:

- `<` replaced with `&lt;`

- `>` replaced with `&gt;`

- `&` replaced with `&amp;`

- `"` replaced with `&quot;`

Note that if you want to insert an attribute value securely, you must quote the attribute value in the HTML template with quotation mark (with `"`, not with `'`):

    <input type=text name=user value="${user?html}">

Note that in HTML pages usually you want to use this built-in for all interpolations. So you can spare a lot of typing and lessen the chances of accidental mistakes by using the `escape` directive.

escaping output
html built-in

##### groups

This is used only with the result of the `matches` built-in. See there...

groups built-in

##### index_of

Returns the index within this string of the first occurrence of the specified substring. For example, `"abcabc"?index_of("bc")` will return 1 (don't forget that the index of the first character is 0). Also, you can specify the index to start the search from: `"abcabc"?index_of("bc", 2)` will return 4. There is no restriction on the numerical value of the second parameter: if it is negative, it has the same effect as if it were zero, and if it is greater than the length of this string, it has the same effect as if it were equal to the length of this string. Decimal values will be truncated to integers.

If the 1st parameter does not occur as a substring in this string (starting from the given index, if you use the second parameter), then it returns -1.

index_of built-in

##### j_string

Escapes the string with the escaping rules of Java language string literals, so it's safe to insert the value into a string literal. Note that it will not add quotation marks around the inserted value; you meant to use this inside the string literal.

All characters under UCS code point 0x20 will be escaped. When they have no dedicated escape sequence in the Java language (like `\n`, `\t`, etc.), they will be replaced with a UNICODE escape (`\uXXXX`).

Example:

    <#assign beanName = 'The "foo" bean.'>
    String BEAN_NAME = "${beanName?j_string}";

will output:

    String BEAN_NAME = "The \"foo\" bean.";

j_string built-in

##### js_string

Escapes the string with the escaping rules of JavaScript language string literals, so it's safe to insert the value into a string literal. Note that it will not add quotation marks around the inserted value; you meant to use this inside the string literal.

Both quotation mark (`"`) and apostrophe-quoate (`'`) are escaped. Starting from FreeMarker 2.3.1, it also escapes `>` as `\>` (to avoid `</script>`).

All characters under UCS code point 0x20 will be escaped. When they have no dedicated escape sequence in JavaScript (like `\n`, `\t`, etc.), they will be replaced with a UNICODE escape (`\uXXXX`).

Example:

    <#assign user = "Big Joe's \"right hand\"">
    <script>
      alert("Welcome ${user?js_string}!");
    </script>

will output:

    <script>
      alert("Welcome Big Joe\'s \"right hand\"!");
    </script>

js_string built-in

##### json_string

Escapes the string with the escaping rules of JSON language string literals, so it's safe to insert the value into a string literal. Note that it will not add quotation marks around the inserted value; you meant to use this inside the string literal.

This will not escape `'` characters, since JSON strings must be quoted with `"`. It will, however escape the `/` (slash) characters as `\/` where they occur directly after a `<`, to avoid `</script>` and such. It will also escape the `>` characters as `\u003E` where they occur directly after `]]`, to avoid exiting an XML `CDATA` section.

All characters under UCS code point 0x20 will be escaped. When they have no dedicated escape sequence in JSON (like `\n`, `\t`, etc.), they will be replaced with a UNICODE escape (`\uXXXX`).

json_string built-in

##### last_index_of

Returns the index within this string of the last (rightmost) occurrence of the specified substring. It returns the index of the first (leftmost) character of the substring. For example: `"abcabc"?last_index_of("ab")` will return 3. Also, you can specify the index to start the search from. For example, `"abcabc"?last_index_of("ab", 2)` will return 0. Note that the second parameter indicates the maximum index of the start of the substring. There is no restriction on the numerical value of the second parameter: if it is negative, it has the same effect as if it were zero, and if it is greater than the length of this string, it has the same effect as if it were equal to the length of this string. Decimal values will be truncated to inegers.

If the 1st parameter does not occur as a substring in this string (before the given index, if you use the second parameter), then it returns -1.

last_index_of built-in

##### length

The number of characters in the string.

length built-in

##### lower_case

The lower case version of the string. For example `"GrEeN MoUsE"?lower_case` will be `"green mouse"`.

lower_case built-in

##### left_pad

This built-in is available since FreeMarker 2.3.1. It doesn't exist in 2.3.

If it's used with 1 parameter, then it inserts spaces on the beginning of the string until it reaches the length that is specified as the parameter. If the string is already as long or longer than the specified length, then it does nothing. For example, this:

    [${""?left_pad(5)}]
    [${"a"?left_pad(5)}]
    [${"ab"?left_pad(5)}]
    [${"abc"?left_pad(5)}]
    [${"abcd"?left_pad(5)}]
    [${"abcde"?left_pad(5)}]
    [${"abcdef"?left_pad(5)}]
    [${"abcdefg"?left_pad(5)}]
    [${"abcdefgh"?left_pad(5)}]

will output this:

    [     ]
    [    a]
    [   ab]
    [  abc]
    [ abcd]
    [abcde]
    [abcdef]
    [abcdefg]
    [abcdefgh]

If it's used with 2 parameters, then the 1st parameter means the same as if you were using the built-in with only 1 parameter, and the second parameter specifies what to insert instead of space characters. For example:

    [${""?left_pad(5, "-")}]
    [${"a"?left_pad(5, "-")}]
    [${"ab"?left_pad(5, "-")}]
    [${"abc"?left_pad(5, "-")}]
    [${"abcd"?left_pad(5, "-")}]
    [${"abcde"?left_pad(5, "-")}]

will output this:

    [-----]
    [----a]
    [---ab]
    [--abc]
    [-abcd]
    [abcde]

The 2nd parameter can be a string whose length is greater than 1. Then the string will be inserted periodically, for example:

    [${""?left_pad(8, ".oO")}]
    [${"a"?left_pad(8, ".oO")}]
    [${"ab"?left_pad(8, ".oO")}]
    [${"abc"?left_pad(8, ".oO")}]
    [${"abcd"?left_pad(8, ".oO")}]

will output this:

    [.oO.oO.o]
    [.oO.oO.a]
    [.oO.oOab]
    [.oO.oabc]
    [.oO.abcd]

The 2nd parameter must be a string value, and it must be at least 1 character long.

left_pad built-in
padding

##### right_pad

This built-in is available since FreeMarker 2.3.1. It doesn't exist in 2.3.

This is the same as `left_pad`, but it inserts the characters at the end of the string instead of the beginning of the string.

Example:

    [${""?right_pad(5)}]
    [${"a"?right_pad(5)}]
    [${"ab"?right_pad(5)}]
    [${"abc"?right_pad(5)}]
    [${"abcd"?right_pad(5)}]
    [${"abcde"?right_pad(5)}]
    [${"abcdef"?right_pad(5)}]
    [${"abcdefg"?right_pad(5)}]
    [${"abcdefgh"?right_pad(5)}]

    [${""?right_pad(8, ".oO")}]
    [${"a"?right_pad(8, ".oO")}]
    [${"ab"?right_pad(8, ".oO")}]
    [${"abc"?right_pad(8, ".oO")}]
    [${"abcd"?right_pad(8, ".oO")}]

This will output this:

    [     ]
    [a    ]
    [ab   ]
    [abc  ]
    [abcd ]
    [abcde]
    [abcdef]
    [abcdefg]
    [abcdefgh]

    [.oO.oO.o]
    [aoO.oO.o]
    [abO.oO.o]
    [abc.oO.o]
    [abcdoO.o]

right_pad built-in
padding

##### contains

This built-in is available since FreeMarker 2.3.1. It doesn't exist in 2.3.

Returns if the substring specified as the parameter to this built-in occurrs in the string. For example:

    <#if "piceous"?contains("ice")>It contains "ice"</#if>

This will output:

    It contains "ice"

contains built-in

##### matches

This is a ``power user'' built-in. Ignore it if you don't know regular expressions.

This built-in will work only if you use Java2 platform 1.4 or later. Otherwise it will stop template processing with error.

This built-in determines if the string exactly matches the pattern. Also, it returns the list of matching sub-strings. The return value is a multi-type value:

- Boolean: `true`, if it the string exactly matches the pattern, otherwise `false`. For example, `"fooo"?matches('fo*')` is `true`, but `"fooo bar"?matches('fo*')` is `false`.

- Sequence: the list of matched substrings of the string. Possibly a 0 length sequence.

For example:

    <#if "fxo"?matches("f.?o")>Matches.<#else>Does not match.</#if>

    <#assign res = "foo bar fyo"?matches("f.?o")>
    <#if res>Matches.<#else>Does not match.</#if>
    Matching sub-strings:
    <#list res as m>
    - ${m}
    </#list>

will print:

    Matches.

    Does not match.
    Matching sub-strings:
    - foo
    - fyo

If the regular expression contains groups (parentheses), then you can access them with the `groups` built-in:

    <#assign res = "aa/rx; ab/r;"?matches("(\\w[^/]+)/([^;]+);")>
    <#list res as m>
    - ${m} is ${m?groups[1]} per ${m?groups[2]}
    </#list>

This will print:

    - aa/rx; is aa per rx
    - ab/r; is ab per r

`matches` accepts an optional 2nd parameter, the flags. Note that it does not support flag `f`, and ignores the `r` flag.

matches built-in

##### number

The string converted to numerical value. The number must be in the same format as you specify numerical values directly in FTL. That is, it must be in the locale independent form, where the decimal separator is dot. In additional the built-in recognizes scientific notation (e.g. `"1.23E6"`, `"1.5e-8"`).

If the string is not in the appropriate format, an error will abort template processing when you try to access this built-in.

Known problem: If you use earlier Java2 platform than v1.3, the built-ins will not recognize + prefix and scientific notation.

type-casting
converting between types
number built-in
string to number
converting string to number
parse string as number

##### replace

It is used to replace all occurrences of a string in the original string with another string. It does not deal with word boundaries. For example:

    ${"this is a car acarus"?replace("car", "bulldozer")}

will print:

    this is a bulldozer abulldozerus

The replacing occurs in left-to-right order. This means that this:

    ${"aaaaa"?replace("aaa", "X")}

will print:

    Xaa

If the 1st parameter is an empty string, then all occurrences of the empty string will be replaced, like `"foo"?replace("","|")` will evaluate to `"|f|o|o|"`.

`replace` accepts an optional flags parameter, as its 3rd parameter.

replace built-in

##### rtf

The string as Rich text (RTF text). That is, the string with all:

- `\` replaced with `\\`

- `{` replaced with `\{`

- `}` replaced with `\}`

rtf built-in
escaping output

##### url

This built-in is available since FreeMarker 2.3.1. It doesn't exist in 2.3.

The string after URL escaping. This means that all non-US-ASCII and reserved URL characters will be escaped with `%XX`. For example:

    <#assign x = 'a/b c'>
    ${x?url}

The output will be (assuming that the charset used for the escaping is an US-ASCII compatible charset):

    a%2Fb%20c

Note that it escapes all reserved URL characters (`/`, `=`, `&`, ...etc), so this encoding can be used for encoding query parameter values, for example:

    <a href="foo.cgi?x=${x?url}&y=${y?url}">Click here...</a>

Above no HTML encoding (`?htm`) was needed, because URL escaping escapes all reserved HTML characters anyway. But watch: always quote the attribute value, and always with normal quotation mark (`"`), never with apostrophe quotation mark (`'`), because apostrophe quotation mark is not escaped by the URL escaping.

To do URL escaping a charset must be chosen that will be used for calculating the escaped parts (`%XX`). If you are HTML page author and you don't really understand this, don't worry: the programmers should configure FreeMarker so that it uses the proper charset by default (programmers: see more below...). If you are a more technical minded user, then you may want to know that the charset used is specified by the `url_escaping_charset` setting, that can be set in template execution time (or, preferably, earlier by the programmers). For example:

    <#--
      This will use the charset specified by the programmers
      before the template execution has started.
    -->
    <a href="foo.cgi?x=${x?url}">foo</a>

    <#-- Use UTF-8 charset for URL escaping from now: -->
    <#setting url_escaping_charset="UTF-8">

    <#-- This will surely use UTF-8 charset -->
    <a href="bar.cgi?x=${x?url}">bar</a>

Furthermore, you can explicitly specify a charset for a single URL escaping as the parameter to the built-in:

    <a href="foo.cgi?x=${x?url('ISO-8895-2')}">foo</a>

If the `url` built-in has no parameter, then it will use the charset specified as the value of the `url_escaping_charset` setting. This setting should be set by the software that encloses FreeMarker (e.g. a Web application framework), because it is not set (`null`) by default. If it is not set, then FreeMarker falls back using the value of the `output_encoding` setting, which is also not set by default, so it is again the task of the enclosing software. If the `output_encoding` setting is not set either, then the parameterless `url` built-in can't be executed, and it will cause execution time error. Of course, the `url` built-in with parameter always works.

output encoding
output charset

It's possible to set `url_escaping_charset` in the template with the `setting` directive, but it is bad practice, at least in true MVC applications. The `output_encoding` setting can't be set with the `setting` directive, so that's surely the task of the enclosing software. You may find more information regarding this here...

url built-in
escaping URL
encoding URL
URL escaping
URL encoding
url_escaping_charset

##### split

It is used to split a string into a sequence of strings along the occurrences of another string. For example:

    <#list "someMOOtestMOOtext"?split("MOO") as x>
    - ${x}
    </#list>

will print:

    - some
    - test
    - text

Note that it is assumed that all occurrences of the separator is before a new item, thus:

    <#list "some,,test,text,"?split(",") as x>
    - "${x}"
    </#list>

will print:

    - "some"
    - ""
    - "test"
    - "text"
    - ""

`split` accepts an optional flags parameter, as its 2nd parameter.

split built-in

##### starts_with

Returns if this string starts with the specified substring. For example `"redhead"?starts_with("red")` returns boolean true. Also, `"red"?starts_with("red")` will return true.

starts_with built-in

##### string (when used with a string value)

Does nothing, just returns the string as-is. The exception is that if the value is a multi-type value (e.g. it is both string and sequence at the same time), then the resulting value will be only a simple string, not a multi-type value. This can be utilized to prevent the artifacts of multi-typing.

##### trim

The string without leading and trailing white-space. Example:

    (${"  green mouse  "?trim})

The output:

    (green mouse)

trim built-in

##### upper_case

The upper case version of the string. For example `"GrEeN MoUsE"` will be `"GREEN MOUSE"`.

upper_case built-in

##### word_list

A sequence that contains all words of the string in the order as they appear in the string. Words are continual character sequences that contain any character but white-space. Example:

    <#assign words = "   a bcd, .   1-2-3"?word_list>
    <#list words as word>[${word}]</#list>

will output:

    [a][bcd,][.][1-2-3]

word_list built-in

##### xhtml

The string as XHTML text. That is, the string with all:

- `<` replaced with `&lt;`

- `>` replaced with `&gt;`

- `&` replaced with `&amp;`

- `"` replaced with `&quot;`

- `'` replaced with `&#39;`

The only difference between this built-in and the `xml` built-in is that the `xhtml` built-in escapes `'` as `&#39;` instead of as `&apos;`, because some older browsers don't interpret `&apos;` correctly.

xhtml built-in
escaping output

##### xml

The string as XML text. That is, the string with all:

- `<` replaced with `&lt;`

- `>` replaced with `&gt;`

- `&` replaced with `&amp;`

- `"` replaced with `&quot;`

- `'` replaced with `&apos;`

xml built-in
escaping output

##### Common flags

Many string built-ins accept an optional string parameter, the so called ``flags''. In this string, each letter influences a certain aspect of the behavior of the built-in. For example, letter `i` means that the built-in should not differentiate the lower and upper-case variation of the same letter. The order of the letters in the flags string is not significant.

This is the complete list of letters (flags):

- `i`: Case insensitive: do not differentiate the lower and upper-case variation of the same letter.

- `f`: First only. That is, replace/find/etc. only the first occurrence of something.

- `r`: The substring to find is a regular expression. FreeMarker uses the variation of regular expressions described at http://java.sun.com/j2se/1.4.1/docs/api/java/util/regex/Pattern.html. This flag will work only if you use Java2 platform 1.4 or later. Otherwise it will cause template processing to stop with error.

  regular expression built-ins

- `m`: Multi-line mode for regular expressions. In multi-line mode the expressions `^` and `$` match just after or just before, respectively, a line terminator or the end of the string. By default these expressions only match at the beginning and the end of the entire string. Note that `^` and `$` doesn't match the line-break character itself.

- `s`: Enables dot-all mode for regular expressions (same as Perl singe-line mode). In dot-all mode, the expression `.` matches any character, including a line terminator. By default this expression does not match line terminators.

- `c`: Permits whitespace and comments in regular expressions.

Example:

    <#assign s = 'foo bAr baar'>
    ${s?replace('ba', 'XY')}
    i: ${s?replace('ba', 'XY', 'i')}
    if: ${s?replace('ba', 'XY', 'if')}
    r: ${s?replace('ba*', 'XY', 'r')}
    ri: ${s?replace('ba*', 'XY', 'ri')}
    rif: ${s?replace('ba*', 'XY', 'rif')}

This outputs this:

    foo bAr XYar
    i: foo XYr XYar
    if: foo XYr baar
    r: foo XYAr XYr
    ri: foo XYr XYr
    rif: foo XYr baar

This is the table of built-ins that use these common flags, and which supports which flags:

Built-in | `i` (ignore case) | `r` (reg. exp.) | `m` (multi-line mode) | `s` (dot-all mode) | `c` (whitesp. and comments) | `f` (first only)
--- | --- | --- | --- | --- | --- | ---
`replace` | Yes | Yes | Only with `r` | Only with `r` | Only with `r` | Yes
`split` | Yes | Yes | Only with `r` | Only with `r` | Only with `r` | No
`match` | Yes | Ignored | Yes | Yes | Yes | No

string built-ins

#### Built-ins for numbers

Related FAQs: Do you have things like 1,000,000 or 1 000 000 instead of 1000000, or something like 3.14 instead of 3,14 or vice versa? See this and this FAQ entry, also note the `c` built-in above.

##### c

This built-in exists since FreeMarker 2.3.3.

This built-in converts a number to string for ``computer audience'' as opposed to human audience. That is, it formats with the rules that programming languages used to use, which is independent of all the locale and number format settings of FreeMarker. It always uses dot as decimal separator, and it never uses grouping separators (like 3,000,000), nor exponential form (like 5E20), nor superfluous leading or trailing 0-s (like 03 or 1.0), nor + sign (like +1). It will print at most 16 digits after the decimal dot, and thus numbers whose absolute value is less than 1E-16 will be shown as 0. This built-in is crucial because be default (like with `${x}`) numbers are converted to strings with the locale (language, country) specific number formatting, which is for human readers (like 3000000 is possibly printed as 3,000,000). When the number is printed not for human audience (e.g., for a database record ID used as the part of an URL, or as invisible field value in a HTML form, or for printing CSS/JavaScript numerical literals) this built-in must be used to print the number (i.e., use `${x?c}` instead of `${x}`), or else the output will be possibly broken depending on the current number formatting settings and locale (like the decimal point is not dot, but comma in many countries) and the value of the number (like big numbers are possibly ``damaged'' by grouping separators).

type-casting
converting between types
format number

##### string (when used with a numerical value)

Converts a number to a string. It uses the default format that the programmer has specified. You can also specify a number format explicitly with this built-in, as it will be shown later.

There are four predefined number formats: `computer`, `currency`, `number`, and `percent`. The exact meaning of these is locale (nationality) specific, and is controlled by the Java platform installation, rather than by FreeMarker, except for `computer`, which uses the same formatting as the `c` built-in. You can use these predefined formats like this:

    <#assign x=42>
    ${x}
    ${x?string}  <#-- the same as ${x} -->
    ${x?string.number}
    ${x?string.currency}
    ${x?string.percent}
    ${x?string.computer}

If your locale is US English, this will certainly produce:

    42
    42
    42
    $42.00
    4,200%
    42

The output of first three expressions is identical because the first two expressions use the default format, which is "number" here. You can change this default using a setting:

    <#setting number_format="currency">
    <#assign x=42>
    ${x}
    ${x?string}  <#-- the same as ${x} -->
    ${x?string.number}
    ${x?string.currency}
    ${x?string.percent}

Will now output:

    $42.00
    $42.00
    42
    $42.00
    4,200%

since the default number format was set to "currency".

Beside the three predefined formats, you can use arbitrary number format patterns written in Java decimal number format syntax:

    <#assign x = 1.234>
    ${x?string("0")}
    ${x?string("0.#")}
    ${x?string("0.##")}
    ${x?string("0.###")}
    ${x?string("0.####")}

    ${1?string("000.00")}
    ${12.1?string("000.00")}
    ${123.456?string("000.00")}

    ${1.2?string("0")}
    ${1.8?string("0")}
    ${1.5?string("0")} <-- 1.5, rounded towards even neighbor
    ${2.5?string("0")} <-- 2.5, rounded towards even neighbor

    ${12345?string("0.##E0")}

outputs this:

    1
    1.2
    1.23
    1.234
    1.234

    001.00
    012.10
    123.46

    1
    2
    2 <-- 1.5, rounded towards even neighbor
    2 <-- 2.5, rounded towards even neighbor

    1.23E4

Following the financial and statistics practice, the rounding goes according the so called half-even rule, which means rounding towards the nearest ``neighbor'', unless both neighbors are equidistant, in which case, it rounds towards the even neighbor. This was visible in the above example if you look at the rounding of 1.5 and of 2.5, as both were rounded to 2, since 2 is even, but 1 and 3 are odds.

Apart from the Java decimal syntax patterns, you can also write `${aNumber?string("currency")}` and like, that will do the same as `${aNumber?string.currency}` and like.

As it was shown for the predefined formats earlier, the default formatting of the numbers can be set in the template:

    <#setting number_format="0.##">
    ${1.234}

outputs this:

    1.23

Note that the number formatting is locale sensitive:

    <#setting locale="en_US">
    US people write:        ${12345678?string(",##0.00")}
    <#setting locale="hu">
    Hungarian people write: ${12345678?string(",##0.00")}

outputs this:

    US people write:        12,345,678.00
    Hungarian people write: 12 345 678,00

type-casting
converting between types
string built-in
format number

##### round, floor, ceiling

The rounding built-ins exist since FreeMarker 2.3.13.

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 neagative infinity)

- `ceiling`: Rounds the number upwards (i.e., towards positive infinity)

Example:

    <#assign testlist=[
      0, 1, -1, 0.5, 1.5, -0.5,
      -1.5, 0.25, -0.25, 1.75, -1.75]>
    <#list testlist as result>
        ${result} ?floor=${result?floor} ?ceiling=${result?ceiling} ?round=${result?round}
    </#list>

Prints:

        0 ?floor=0 ?ceiling=0 ?round=0
        1 ?floor=1 ?ceiling=1 ?round=1
        -1 ?floor=-1 ?ceiling=-1 ?round=-1
        0.5 ?floor=0 ?ceiling=1 ?round=1
        1.5 ?floor=1 ?ceiling=2 ?round=2
        -0.5 ?floor=-1 ?ceiling=0 ?round=0
        -1.5 ?floor=-2 ?ceiling=-1 ?round=-1
        0.25 ?floor=0 ?ceiling=1 ?round=0
        -0.25 ?floor=-1 ?ceiling=0 ?round=0
        1.75 ?floor=1 ?ceiling=2 ?round=2
        -1.75 ?floor=-2 ?ceiling=-1 ?round=-2

These built-ins may be useful in pagination operations and like. If you just want to display numbers in rounded form, then you should rather use the `string` built-in or the `number_format` setting.

rounding
floor built-in
ceiling built-in
round built-in
number built-ins

#### Built-ins for dates

##### string (when used with a date value)

This built-in converts a date to a string, with the specified formatting. (when the default format dictated by the `date_format`, `time_format` and `datetime_format` settings of FreeMarker are good for you, then you do not need this built-in.)

The format can be one of the predefined formats, or you can specify the formatting pattern explicitly.

The predefined formats are `short`, `medium`, `long`, and `full` which define how verbose the resulting text will be. For example, if the locale of the output is U.S. English, and the time zone is the U.S. Pacific Time zone, then this:

    ${openingTime?string.short}
    ${openingTime?string.medium}
    ${openingTime?string.long}
    ${openingTime?string.full}

    ${nextDiscountDay?string.short}
    ${nextDiscountDay?string.medium}
    ${nextDiscountDay?string.long}
    ${nextDiscountDay?string.full}

    ${lastUpdated?string.short}
    ${lastUpdated?string.medium}
    ${lastUpdated?string.long}
    ${lastUpdated?string.full}

will prints something like this:

    12:45 PM
    12:45:09 PM
    12:45:09 PM CEST
    12:45:09 PM CEST

    4/20/07
    Apr 20, 2007
    April 20, 2007
    Friday, April 20, 2007

    4/20/07 12:45 PM
    Apr 20, 2007 12:45:09 PM
    April 20, 2007 12:45:09 PM CEST
    Friday, April 20, 2007 12:45:09 PM CEST

The exact meaning of `short`, `medium`, `long`, and `full` depends on the current locale (language). Furthermore, it is specified not by FreeMarker, but the Java platform implementation you run FreeMarker on.

For dates that contains both date and time part, you can specify the length of the date and time part independently:

    ${lastUpdated?string.short_long} <#-- short date, long time -->
    ${lastUpdated?string.medium_short} <#-- medium date, short time -->

will output:

    4/8/03 9:24:44 PM PDT
    Apr 8, 2003 9:24 PM

Note that `?string.short` is the same as `?string.short_short`, `?string.medium` is the same as `?string.medium_medium`, etc.

Unfortunately, because of the limitations of the Java platform, it can happen that you have date variables in the data-model, where FreeMarker can't decide if the variable stores only date part (year, month, day), only time part (hour, minute, second, millisecond) or both. In this case, FreeMarker don't know how to display the date when you write something like `${lastUpdated?string.short}` or simply `${lastUpdated}`, and thus it will stop with error. To prevent this, you can help FreeMarker with the `?date`, `?time` and `?datetime` built-ins. For example: `${lastUpdated?datetime?string.short}`. Ask the programmer if certain variables of the data-model has this problem, or always use `?date`, `?time` and `?datetime` built-ins.

Instead of using the predefined formats, you can specify the formatting pattern explicitly with `?string(pattern_string)`. The pattern uses Java date format syntax. Example:

    ${lastUpdated?string("yyyy-MM-dd HH:mm:ss zzzz")}
    ${lastUpdated?string("EEE, MMM d, ''yy")}
    ${lastUpdated?string("EEEE, MMMM dd, yyyy, hh:mm:ss a '('zzz')'")}

will output:

    2003-04-08 21:24:44 Pacific Daylight Time
    Tue, Apr 8, '03
    Tuesday, April 08, 2003, 09:24:44 PM (PDT)

Unlike with the predefined formats, you never need to use `?date`, `?time` and `?datetime` with explicitly given patterns, since with the pattern you tell FreeMarker what parts of the date to show. However, FreeMarker will trust you blindly, so you can show "noise" if you display parts that are actually not stored in the variable. For example, `${openingTime?string("yyyy-MM-dd hh:mm:ss a")}`, where `openingTime` stores only time, will display `1970-01-01 09:24:44 PM`.

The pattern string also can be `"short"`, `"medium"`, ..., `"short_medium"`, ...etc. These are the same as if you would use the predefined formats with the dot syntax: `someDate?string("short")` and `someDate?string.short` are equivalent.

See also: the interpolation of dates

type-casting
converting between types
string built-in
format date
converting date to string
converting time to string
time to string
date to string

##### date, time, datetime (when used with a date value)

These built-ins can be used to specify which parts of the date variable are in use:

- `date`: Only the year, month and day parts are used.

- `time`: Only the hour, minute, second and millisecond parts are used.

- `datetime`: Both the date and the time parts are used.

In optimal case, you do not need to use these built-ins. Unfortunately, because of the technical limitations of the Java platform, FreeMarker sometimes can't find out which parts of the date are in use (i.e. only the year+month+day, or only hour+minute+second+millisecond, or both); ask the programmers which variables has this problem. If FreeMarker has to execute an operation where this information is needed -- such as displaying the date as text -- but it does not know which parts are in use, it will stop with error. This is when you have to use these built-ins. For example, assume `openingTime` is a such problematic variable:

    <#assign x = openingTime> <#-- no problem can occur here -->
    ${openingTime?time} <#-- without ?time it would fail -->
    <#-- For the sake of better understanding, consider this: -->
    <#assign openingTime = openingTime?time>
    ${openingTime} <#-- this will work now -->

There is another usage of these built-ins: to truncate dates. For example:

    Last updated: ${lastUpdated} <#-- assume that lastUpdated is a date-time value -->
    Last updated date: ${lastUpdated?date}
    Last updated time: ${lastUpdated?time}

will output something like:

    Last updated: 04/25/2003 08:00:54 PM
    Last updated date: 04/25/2003
    Last updated time: 08:00:54 PM

If the left side of the `?` is string, then these built-ins convert strings to date variable.

type-casting
converting between types
date built-in
time built-in
datetime built-in

##### iso_...

These built-ins convert a date, time or date-time value to string that follows ISO 8601 "extended" format. This built-in has several variations: `iso_utc`, `iso_local`, `iso_utc_nz`, `iso_local_nz`, `iso_utc_m`, `iso_utc_m_nz`, etc. The name is constructed from the following words in this order, each separated with a `_` from the next:

1. `iso` (required)

2. Either `utc` or `local` (required (except when it's given with a parameter, but see that later)): Specifies whether you want to print the date according to UTC or according the current time zone. The current time zone is decided by the `time_zone` FreeMarker setting and is normally configured by the programmers outside the templates (but it can also be set in a template, like `<#setting time_zone="America/New_York">` for example).

3. Either `h` or `m` or `ms` (optional): The accuracy of the time part. When omitted, it defaults to seconds accuracy (like `12:30:18`). `h` means hours accuracy (like `12`), `m` means minutes accuracy (`12:30`), and `ms` means milliseconds accuracy (`12:30:18.25`, where we have 250 ms). Note that when using `ms`, the milliseconds are displayed as fraction seconds (following the standard) and will not have trailing `0`-s. Thus, if the the millisecond part happens to be `0`, the whole fraction second part will be omitted. Also note that the fraction seconds are always separated with a dot , not with comma (to follow the Web conventions and the XML Schema date/time format).

4. `nz` (optional): When present, the time zone offset (like `+02:00` or or `-04:30` or `Z`) will not be displayed. Otherwise it will be displayed, except for date-only values (as dates with zone offset doesn't appear in ISO 8601:2004). Since FreeMarker 2.3.19, the offset always contains the minutes for XML Schema date/time format compliance.

Example:

    <#assign aDateTime = .now>
    <#assign aDate = aDateTime?date>
    <#assign aTime = aDateTime?time>

    Basic formats:
    ${aDate?iso_utc}
    ${aTime?iso_utc}
    ${aDateTime?iso_utc}

    Different accuracies:
    ${aTime?iso_utc_ms}
    ${aDateTime?iso_utc_m}

    Local time zone:
    ${aDateTime?iso_local}

A possible output (depends on current time and time zone):

    Basic formats:
    2011-05-16
    21:32:13Z
    2011-05-16T21:32:13Z

    Different accuracies:
    21:32:13.868Z
    2011-05-16T21:32Z

    Local time zone:
    2011-05-16T23:32:13+02:00

There is yet another group of `iso_...` built-in variants, where you omit the `local` or `utc` word from the name and instead specify the time zone as a parameter to the built-in. Example:

    <#assign aDateTime = .now>
    ${aDateTime?iso("UTC")}
    ${aDateTime?iso("GMT-02:30")}
    ${aDateTime?iso("Europe/Rome")}

    The usual variations are supported:
    ${aDateTime?iso_m("GMT+02")}
    ${aDateTime?iso_m_nz("GMT+02")}
    ${aDateTime?iso_nz("GMT+02")}

A possible output (depends on current time and time zone):

    2011-05-16T21:43:58Z
    2011-05-16T19:13:58-02:30
    2011-05-16T23:43:58+02:00

    The usual variations are supported:
    2011-05-16T23:43+02:00
    2011-05-16T23:43
    2011-05-16T23:43:58

If the time zone parameter can't be interpreted, the template processing will be terminated with error.

The parameter can be a `java.util.TimeZone` object too (which is possibly the return value of a Java method, or it's in the data-model), not just a string.

type-casting
converting between types
iso built-in
iso_... built-ins
format date
converting date to string
converting time to string
time to string
date to string
ISO 8601
date built-ins
time built-ins

#### Built-ins for booleans

##### string (when used with a boolean value)

Converts a boolean to a string. You can use it in two ways:

- As `foo?string`: This will convert the boolean to string using the default strings for representing true and false values. By default, true is rendered as `"true"` and false is rendered as `"false"`. This is mostly useful if you generate source code with FreeMarker, since the values are not locale (language, country) sensitive. To change these default strings, you can use the `boolean_format` setting. Note, that if the variable is multi-type variable that is both boolean and string, then the string value of the variable will be returned.

- As `foo?string("yes", "no")`: This will return the first parameter (here: `"yes"`) if the boolean is true, otherwise the second parameter (here: `"no"`). Note that the return value is always a string; if the parameters were numbers, they would be converted to strings first.

boolean printing
type-casting
converting between types
string built-in
format boolean
boolean built-ins

#### Built-ins for sequences

##### first

The first subvariable of the sequence. Template processing will die with error if the sequence is empty.

first built-in

##### last

The last subvariable of the sequence. Template processing will die with error if the sequence is empty.

last built-in

##### seq_contains

This built-in is available since FreeMarker 2.3.1. It doesn't exist in 2.3.

The `seq_` prefix is required in the built-in name to differentiate it from the `contains` built-in that searches a substring in a string (since a variable can be both string and sequence on the same time).

Tells if the sequence contains the specified value. It has 1 parameter, the value to find. Example:

    <#assign x = ["red", 16, "blue", "cyan"]>
    "blue": ${x?seq_contains("blue")?string("yes", "no")}
    "yellow": ${x?seq_contains("yellow")?string("yes", "no")}
    16: ${x?seq_contains(16)?string("yes", "no")}
    "16": ${x?seq_contains("16")?string("yes", "no")}

The output will be:

    "blue": yes
    "yellow": no
    16: yes
    "16": no

To find the value the built-in uses FreeMarker's comparison rules (as if you was using `==` operator), except that comparing two values of different types or of types for which FreeMarker doesn't support comparison will not cause error, just will be evaluated as the two values are not equal. Thus, you can use it only to find scalar values (i.e. string, number, boolean or date/time values). For other types the result will be always `false`.

For fault tolerance, this built-in also works with collections.

seq_contains built-in

##### seq_index_of

This built-in is available since FreeMarker 2.3.1. It doesn't exist in 2.3.

The `seq_` prefix is required in the built-in name to differentiate it from the `index_of` built-in that searches a substring in a string (since a variable can be both string and sequence on the same time).

Returns the index of the first occurrence of a value in the sequence, or `-1` if the sequence doesn't contain the specified value. The value to find is specified as the first parameter. For example this template:

    <#assign colors = ["red", "green", "blue"]>
    ${colors?seq_index_of("blue")}
    ${colors?seq_index_of("red")}
    ${colors?seq_index_of("purple")}

will output this:

    2
    0
    -1

To find the value the built-in uses FreeMarker's comparison rules (as if you was using `==` operator), except that comparing two values of different types or of types for which FreeMarker doesn't support comparison will not cause error, just will be evaluated as the two values are not equal. Thus, you can use it only to find scalar values (i.e. string, number, boolean or date/time values). For other types the result will be always `-1`.

The index where the searching is started can be optionally given as the 2nd parameter. This may be useful if the same item can occur for multiple times in the same sequence. There is no restriction on the numerical value of the second parameter: if it is negative, it has the same effect as if it were zero, and if it is greater than the length of the sequence, it has the same effect as if it were equal to the length of the sequence. Decimal values will be truncated to integers. For example:

    <#assign names = ["Joe", "Fred", "Joe", "Susan"]>
    No 2nd param: ${names?seq_index_of("Joe")}
    -2: ${names?seq_index_of("Joe", -2)}
    -1: ${names?seq_index_of("Joe", -1)}
     0: ${names?seq_index_of("Joe", 0)}
     1: ${names?seq_index_of("Joe", 1)}
     2: ${names?seq_index_of("Joe", 2)}
     3: ${names?seq_index_of("Joe", 3)}
     4: ${names?seq_index_of("Joe", 4)}

will output this:

    No 2nd param: 0
    -2: 0
    -1: 0
     0: 0
     1: 2
     2: 2
     3: -1
     4: -1

seq_index_of built-in

##### seq_last_index_of

This built-in is available since FreeMarker 2.3.1. It doesn't exist in 2.3.

The `seq_` prefix is required in the built-in name to differentiate it from the `last_index_of` built-in that searches a substring in a string (since a variable can be both string and sequence on the same time).

Returns the index of the last occurrence of a value in the sequence, or `-1` if the sequence doesn't contain the specified value. That is, it is the same as `seq_index_of`, just it searches backward starting from the last item of the sequence. It also supports the optional 2nd parameter that specifies the index where the searching is started. For example:

    <#assign names = ["Joe", "Fred", "Joe", "Susan"]>
    No 2nd param: ${names?seq_last_index_of("Joe")}
    -2: ${names?seq_last_index_of("Joe", -2)}
    -1: ${names?seq_last_index_of("Joe", -1)}
     0: ${names?seq_last_index_of("Joe", 0)}
     1: ${names?seq_last_index_of("Joe", 1)}
     2: ${names?seq_last_index_of("Joe", 2)}
     3: ${names?seq_last_index_of("Joe", 3)}
     4: ${names?seq_last_index_of("Joe", 4)}

will output this:

    No 2nd param: 2
    -2: -1
    -1: -1
     0: 0
     1: 0
     2: 2
     3: 2
     4: 2

seq_last_index_of built-in

##### reverse

The sequence with reversed order.

reverse built-in

##### size

The number of subvariables 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.

size built-in

##### 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 subvariables are strings, or if all subvariables are numbers, or if all subvariables are date values (date, time, or date+time), or if all subvariables are booleans (since 2.3.17). If the subvariables 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

sort built-in
sequence sorting

##### sort_by

Returns the sequence of hashes sorted by the given hash subvariable in ascending order. (For descending order use this and then the `reverse` built in.) The rules are the same as with the `sort` built-in, except that the subvariables of the sequence must be hashes, and you have to give the name of a hash subvariable that will decide the order. For example:

    <#assign ls = [
      {"name":"whale", "weight":2000},
      {"name":"Barbara", "weight":53},
      {"name":"zeppelin", "weight":-200},
      {"name":"aardvark", "weight":30},
      {"name":"beetroot", "weight":0.3}
    ]>
    Order by name:
    <#list ls?sort_by("name") as i>
    - ${i.name}: ${i.weight}
    </#list>

    Order by weight:
    <#list ls?sort_by("weight") as i>
    - ${i.name}: ${i.weight}
    </#list>

will print (with US locale at least):

    Order by name:
    - aardvark: 30
    - Barbara: 53
    - beetroot: 0.3
    - whale: 2000
    - zeppelin: -200

    Order by weight:
    - zeppelin: -200
    - beetroot: 0.3
    - aardvark: 30
    - Barbara: 53
    - whale: 2000

If the subvariable that you want to use for the sorting is on a deeper level (that is, if it is a subvariable of a subvariable and so on), then you can use a sequence as parameter, that specifies the names of the subvariables that lead down to the desired subvariable. For example:

    <#assign members = [
        {"name": {"first": "Joe", "last": "Smith"}, "age": 40},
        {"name": {"first": "Fred", "last": "Crooger"}, "age": 35},
        {"name": {"first": "Amanda", "last": "Fox"}, "age": 25}]>
    Sorted by name.last:
    <#list members?sort_by(['name', 'last']) as m>
    - ${m.name.last}, ${m.name.first}: ${m.age} years old
    </#list>

will print (with US locale at least):

    Sorted by name.last:
    - Crooger, Fred: 35 years old
    - Fox, Amanda: 25 years old
    - Smith, Joe: 40 years old

sort_by built-in
sequence sorting

##### chunk

This built-in exists since FreeMarker 2.3.3.

This built-in splits a sequence into multiple sequences of the size given with the 1st parameter to the built-in (like `mySeq?chunk(3)`). The result is the sequence of these sequences. The last sequence is possibly shorter than the given size, unless the 2nd parameter is given (like `mySeq?chunk(3, '-')`), that is the item used to make up the size of the last sequence to the given size. Example:

    <#assign seq = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']>

    <#list seq?chunk(4) as row>
      <#list row as cell>${cell} </#list>
    </#list>

    <#list seq?chunk(4, '-') as row>
      <#list row as cell>${cell} </#list>
    </#list>

The output will be:

      a b c d
      e f g h
      i j

      a b c d
      e f g h
      i j - -

This built in is mostly for outputting sequnces in tabular/columnar format. When used with HTML tables, the 2nd parameter is often `"\xA0"` (that is the code of the no-break space character, also known as ``nbsp''), so the border of the empty TD-s will not be missing.

The 1st parameter must be a number that is at least 1. If the number is not integer, it will be silently rounded down to integer (i.e. both 3.1 and 3.9 will be rounded to 3). The 2nd parameter can be of any type and value.

chunk built-in
tabular printing of sequences
columnar printing of sequences
sequence built-ins

#### 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;

Since hashes do not define an order for their subvariables in general, the order in which key names are returned can be arbitrary. However, some hashes maintain a meaningful order (ask the programmer if a certain hash does that or not). For example, hashes created with the above `{...}` syntax preserve the same order as you have specified the subvariables.

keys built-in

##### 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).

As of the order in which the values are returned, the same applies as with the `keys` built-in; see there.

values built-in
hash built-ins

#### Built-ins for nodes (for XML)

Note that the variables returned by these built-ins are generated by the node variable implementation it is used with. This means that the returned variables can have extra features in additional to what it stated here, for example, with the XML DOM nodes the sequence retuned by the `children` built-in also can be used as hash and maybe as string, as it is described in the part about XML processing.

##### children

A sequence that contains all of this node's child nodes (i.e. immediate descendant nodes).

XML: This is almost the same as special hash key `*`, except that it returns all nodes, not only elements. So the possible children are element nodes, text nodes, comment nodes, processing instruction nodes, etc. but not attribute nodes. Attribute nodes are excluded from the sequence.

children built-in

##### parent

The node that is this node's immediate parent in the node tree. The root node has no parent node, so for the root node, the expression `node?parent??` evaluates to `false`.

XML: Note that the value returned by this built-in is also a sequence (same as the result of XPath expression `..`, when you write `someNode[".."]`). Also note that for attribute nodes, it returns the element the attribute belongs to, despite that attribute nodes are not counted as children of the element.

parent built-in

##### root

The node that is the root of the tree of nodes to which this node belongs.

XML: According to W3C, the root of an XML document is not the topmost element node, but the document itself, which is the parent of the topmost element. For example, if you want to get the topmost element of the XML (the so called ``document element''; do not mix it with the ``document''), which is called `foo`, then you have to write `someNode?root.foo`. If you write just `someNode?root`, then you get the document itself, and not the document element.

root built-in

##### ancestors

A sequence that contains all the node's ancestors, starting with the immediate parent and ending with the root node. The result of this built-in is also a method, by which you can filter the result with the full-qualified name of the node. For example as `node?ancestors("section")` to get the sequence of all ancestors with name `section`.

ancestors built-in

##### node_name

Returns the string that is used to determine what user-defined directive to invoke to handle this node when it is ``visited''. See: the visit and recurse directives.

XML: If the node is an element or attribute, then the string will be the local (prefix free) name of the element or attribute. Otherwise the name usually starts with `@` followed by the node type. See this table. Note that this node name is not the same as the node name returned in the DOM API; the goal of FreeMarker node names is to give the name of the used-defined directive that will process the node.

node_name built-in

##### node_type

A string that describes the type of node this is. FreeMarker does not define the exact meaning of node type; it depends on what your variables are modeling. It's possible that a node doesn't support node type at all. In this case, the built-in evaluates to an undefined value, so you can't use the returned value. (You can still check if a node supports the type property with `node?node_type??`.)

XML: The possible values are: `"attribute"`, `"text"`, `"comment"`, `"document_fragment"`, `"document"`, `"document_type"`, `"element"`, `"entity"`, `"entity_reference"`, `"notation"`, `"pi"`. Note that a there is no `"cdata"` type, because CDATA is considered as plain text node.

node_type built-in

##### node_namespace

Returns the namespace string of the node. FreeMarker does not define the exact meaning of node namespace; it depends on what your node variables are modeling. It's possible that a node doesn't have any node namespace defined. In this case, the built-in should evaluate to undefined variable (i.e. `node?node_namespace??` is `false`), so you can't use the returned value.

XML: In the case of XML, it's the XML namespace URI (such as `"http://www.w3.org/1999/xhtml"`). If an element or attribute node does not use XML namespace, then this built-in evaluates to an empty string. For other XML nodes this built-in always return undefined variable.

node_namespace built-in
node built-ins

#### Seldom used and expert built-ins

These are the built-ins that normally you should not use, but in exceptional situations (debugging, advanced macros) they can be useful. If you need to use these in your normal page templates, you may revisit the data-model so you don't need to use these.

##### byte, double, float, int, long, short

Returns a `SimpleNumber` which contains the same value as the original variable, but uses `java.lang.Type` for the internal representation of the value. This is useful if a method is overloaded, or if a `TemplateModel` unwrapper has problem with automatically choosing the suitable `java.lang.*` type. Note that since version 2.3.9 the unwrapper has been improved substantially, so you will hardly ever need to use these built-ins to convert between numerical types, except for resolving ambiguity in overloaded method invocation.

The `long` built-in can also be used with date, time and date-time values to get the value as `java.util.Date.getTime()` would return. This is useful if you have to call a Java methods that expect a timestamp as a `long`. This conversion is not automatic.

type-casting
converting between types
byte built-in
double built-in
float built-in
int built-in
long built-in
short built-in
converting date to long
date to long

##### number_to_date, number_to_time, number_to_datetime

These are used to convert a number (usually a Java `long`) to a date, time or date-time, respectively. This does them same as `new java.util.Date(long)` in Java, that is, the number is interpreted as the milliseconds passed since the epoch. The number can be anything and of any type as far as its value fits into a `long`. If the number isn't a whole number, it will be rounded to whole with half-up rule. This conversion is not automatic.

Example:

    ${1305575275540?number_to_datetime}
    ${1305575275540?number_to_date}
    ${1305575275540?number_to_time}

The output will be something like this (depending on the current locale and time zone):

    May 16, 2011 3:47:55 PM
    May 16, 2011
    3:47:55 PM

type-casting
converting between types
number_to_date built-in
number_to_datetime built-in
number_to_time built-in
converting long to date
long to date

##### eval

This built-in evaluates a string as an FTL expression. For example `"1+2"?eval` returns number 3.

eval
evaluate string

##### has_content

It is `true` if the variable exists (and isn't Java `null`) and is not ``empty'', otherwise it is `false`. The meaning of ``empty'' depends on the concrete case. This follows intuitive common-sense ideas. The following are empty: a string with 0 length, sequence or hash with no subvariables, a collection which has passed the last element. If the value is not a string or sequence or hash or collection, then it counts as non-empty if it's a number or a date or a boolean (e.g. `0` and `false` are not empty), otherwise it counts as empty. Note that when your data-model implements multiple template model interfaces you may get unexpected results. However, when in doubt you can use always use `expr!?size > 0` or `expr!?length > 0` instead of `expr?has_content`.

This buit-in is exceptional in that you can use the parentheses trick like with the default value operator. That is, you can write both `product.color?has_content` and `(product.color)?has_content`. The first doesn't handle the case when `product` is missing, the last does.

has_content built-in

##### interpret

This built-in interprets a string as a FTL template, and returns an user-defined directive that - when applied to any block - executes the template just as if it was included at that point. Example:

    <#assign x=["a", "b", "c"]>
    <#assign templateSource = r"<#list x as y>${y}</#list>">
    <#-- Note: That r was needed so that the ${y} is not interpreted above -->
    <#assign inlineTemplate = templateSource?interpret>
    <@inlineTemplate />

The output:

    abc

As you can see, `inlineTemplate` is a user-defined directive that, when executed, runs the template that was generated on-the-fly using the `interpret`.

You can also apply this built-in to a two-element sequence. In this case the first element of the sequence is the template source, and the second element is a name for the inline template. It can be useful to give an explicit name to the inline template for debugging purposes. So, you could have written:

    <#assign inlineTemplate = [templateSource, "myInlineTemplate"]?interpret>

as well in the above template. Note that giving the inline template a name has no immediate effect - it is only useful as an extra bit of information if you get an error report.

interpret built-in

##### is_...

These built-ins check the type of a variable, and returns `true` or `false` depending on the type. The list of `is_...` built-ins:

Built-in | Returns `true` if the value is a ...
--- | ---
`is_string` | string
`is_number` | number
`is_boolean` | boolean
`is_date` | date (all types: date-only, time-only and date-time)
`is_method` | method
`is_transform` | transform
`is_macro` | macro
`is_hash` | hash
`is_hash_ex` | extended hash (i.e. supports `?keys` and `?values`)
`is_sequence` | sequence
`is_collection` | collection
`is_enumerable` | sequence or collection
`is_indexable` | sequence
`is_directive` | Whatever kind of directive (for example a macro, or `TemplateDirectiveModel`, `TemplateTransformModel`, etc.)
`is_node` | node

is_... built-in
type checking

##### namespace

This built-in returns the namespace (i.e. the ``gate'' hash to the namespace) associated with a macro variable. You can use it with macros only.

namespace built-in

##### new

This is to create a variable of a certain `TemplateModel` implementation.

On the left side of `?` you specify a string, the full-qualified class name of a `TemplateModel` implementation. The result is a method variable that calls the constructor, and returns the new variable.

Example:

    <#-- Creates an user-defined directive be calling the parameterless constructor of the class -->
    <#assign word_wrapp = "com.acmee.freemarker.WordWrapperDirective"?new()>
    <#-- Creates an user-defined directive be calling the constructor with one numerical argument -->
    <#assign word_wrapp_narrow = "com.acmee.freemarker.WordWrapperDirective"?new(40)>

For more information about how the constructor parameters are unwrapped and how overloaded constructor is chosen, read:

This built-in can be a security concern because the template author can create arbitrary Java objects and then use them, as far as they implement `TemplateModel`. Also the template author can trigger static initialization for classes that don't even implement `TemplateModel`. You can (since 2.3.17) restrict the classes accessible with this built-in using `Configuration.setNewBuiltinClassResolver(TemplateClassResolver)` or the `new_builtin_class_resolver` setting. See the Java API docs for more information. If you are allowing not-so-much-trusted users to upload templates then you should definitely look into this topic.

instantiating variable
new built-in
built-in

### Directive Reference

#### Alphabetical index

- assign

- attempt

- break: in switch, in list

- case

- compress

- default

- else

- elseif

- escape

- fallback

- function

- flush

- ftl

- global

- if

- import

- include

- list

- local

- lt

- macro

- nested

- noescape

- nt

- recover

- recurse

- return: in macro, in function

- rt

- setting

- stop

- switch

- t

- User-defined directive (<@...>)

- visit

If you don't find a directive here that you have seen in a working template, probably you will find it in:

directive

#### if, else, elseif

##### Synopsis

    <#if condition>
      ...
    <#elseif condition2>
      ...
    <#elseif condition3>
      ...
    ...
    <#else>
      ...
    </#if>

Where:

- `condition`, `condition2`, ...etc.: Expression evaluates to a boolean value.

##### Description

You can use `if`, `elseif` and `else` directives to conditionally skip a section of the template. The `condition`-s must evaluate to a boolean value, or else an error will abort template processing. The `elseif`-s and `else`-s must occur inside `if` (that is, between the `if` start-tag and end-tag). The `if` can contain any number of `elseif`-s (including 0) and at the end optionally one `else`. Examples:

`if` with 0 `elseif` and no `else`:

    <#if x == 1>
      x is 1
    </#if>

`if` with 0 `elseif` and `else`:

    <#if x == 1>
      x is 1
    <#else>
      x is not 1
    </#if>

`if` with 2 `elseif` and no `else`:

    <#if x == 1>
      x is 1
    <#elseif x == 2>
      x is 2
    <#elseif x == 3>
      x is 3
    </#if>

`if` with 3 `elseif` and `else`:

    <#if x == 1>
      x is 1
    <#elseif x == 2>
      x is 2
    <#elseif x == 3>
      x is 3
    <#elseif x == 4>
      x is 4
    <#else>
      x is not 1 nor 2 nor 3 nor 4
    </#if>

To see more about boolean expressions, see: .

You can nest `if` directives (of course):

    <#if x == 1>
      x is 1
      <#if y == 1>
        and y is 1 too
      <#else>
        but y is not
      </#if>
    <#else>
      x is not 1
      <#if y < 0>
        and y is less than 0
      </#if>
    </#if>

How to test if x is greater than 1? `<#if x > 1>` will be wrong, as FreeMarker will interpret the first `>` as the end of the tag. Thus, either write `<#if (x > 1)>` or `<#if x &gt; 1>`.

if directive
else directive
elseif directive

#### switch, case, default, break

##### Synopsis

    <#switch value>
      <#case refValue1>
        ...
        <#break>
      <#case refValue2>
        ...
        <#break>
      ...
      <#case refValueN>
        ...
        <#break>
      <#default>
        ...
    </#switch>

Where:

- `value`, `refValue1`, etc.: Expressions evaluates to scalars of the same type.

##### Description

The usage of this directive is not recommended, as it is error-prone because of the fall-through behavior. Use `elseif`-s instead unless you want to exploit the fall-through behavior.

Switch is used to choose a fragment of template depending on the value of an expression:

    <#switch being.size>
      <#case "small">
         This will be processed if it is small
         <#break>
      <#case "medium">
         This will be processed if it is medium
         <#break>
      <#case "large">
         This will be processed if it is large
         <#break>
      <#default>
         This will be processed if it is neither
    </#switch>

Inside the `switch` must be one or more `<#case value>`, and after all such `case` tags optionally one `<#default>`. When FM reaches the `switch` directive, it chooses a `case` directive where `refValue` equals with `value` and continues the processing of the template there. If there is no `case` directive with appropriate value then it continues processing at the `default` directive if that exists, otherwise it continues the processing after the end-tag of `switch`. And now comes the confusing thing: when it has chosen a `case` directive, it will continue the processing there, and will go ahead until it reaches a `break` directive. That is, it will not automatically leave the `switch` directive when it reaches another `case` directive or the `<#default>` tag. Example:

    <#switch x>
      <#case x = 1>
        1
      <#case x = 2>
        2
      <#default>
        d
    </#switch>

If `x` is 1, then it will print 1 2 d; if `x` is 2 then it will print 2 d; if `x` is 3 then it will print d. This is the mentioned fall-through behavior. The `break` tag instructs FM to immediately skip past the `switch` end-tag.

switch directive
case directive
default directive
break directive

#### list, break

##### Synopsis

    <#list sequence as item>
        ...
    </#list>

Where:

- `sequence`: Expressions evaluates to a sequence or collection

- `item`: Name of the loop variable (not an expression)

##### Description

You can use the `list` directive to process a section of template for each variable contained within a sequence. The code between the start-tag and end-tag will be processed for the 1st subvariable, then for the 2nd subvariable, then for the 3rd subvariable, etc until it passes the last one. For each such iteration the loop variable will contain the current subvariable.

There are two special loop variables available inside the list loop:

- `item_index`: This is a numerical value that contains the index of the current item being stepped over in the loop.

- `item_has_next`: Boolean value that tells if the current item the last in the sequence or not.

Example 1:

    <#assign seq = ["winter", "spring", "summer", "autumn"]>
    <#list seq as x>
      ${x_index + 1}. ${x}<#if x_has_next>,</#if>
    </#list>

will output:

      1. winter,
      2. spring,
      3. summer,
      4. autumn

Example 2: You can use `list` to count between two numbers, using a numerical range sequence expression:

    <#assign x=3>
    <#list 1..x as i>
      ${i}
    </#list>

The output will be:

      1
      2
      3

Note that the above example will not work as you may expected if `x` is 0, as then it will print 0 and -1.

You can leave the `list` loop before it passes the last subvariable of the sequence with the `break` directive. For example this will print ``winter'' and ``spring'' only:

    <#list seq as x>
      ${x}
      <#if x = "spring"><#break></#if>
    </#list>

Note that if you turn on the classic compatible mode, then the `list` accepts a scalar as well and treats it as a single-element sequence.

In general, it is best to avoid using collection that wraps an `Iterator` as parameters to `list` and use collection that wraps `java.util.Collection` or sequence whenever possible. There are situations however, when you only have an `Iterator` at your disposal. Note that if you pass an collection that wraps an `Iterator` to the `list`, you can iterate over its elements only once since `Iterator`s are by their nature one-off objects. When you try to list a such collection variable for the second time, an error will abort template processing.

list directive
break directive
sequence iterate

#### include

##### Synopsis

    <#include path>
    or
    <#include path options>

Where:

- `path`: The path of the file to include; an expression that evaluates to a string. (With other words, it doesn't have to be a fixed string, it can also be something like, for example, `profile.baseDir + "/menu.ftl"`.)

- `options`: One or more of these: `encoding=encoding`, `parse=parse`

  - `encoding`: Expression evaluates to string

  - `parse`: Expression evaluates to boolean (also accepts a few string values for backward compatibility)

##### Description

You can use it to insert another FreeMarker template file (specified by the `path` parameter) into your template. The output from the included template is inserted at the point where the `include` tag occurs. The included file shares the variables with the including template, similarly like if it was copy-pasted into it. The `include` directive is not replaced by the content of the included file, it just processes the included file each time when FreeMarker reaches the `include` directive in the course of template processing. So for example if the `include` is inside a `list`loop, you can specify different file names in each cycle.

This directive is not be confused with the JSP (Servlet) include, as it doesn't involve the Servlet container at all, just processes another FreeMarker template, without "leaving" FreeMarker. Regarding how to do a "JSP include" read this...

The `path` parameter can be a relative path like `"foo.ftl"` and `"../foo.ftl"`, or an absolute like `"/foo.ftl"`. Relative paths are relative to the directory of the template that uses the `import` directive. Absolute paths are relative to a base (often referred as the ''root directory of the templates'') that the programmer defines when he configures FreeMarker.

This is different than the way it worked prior FreeMarker 2.1, where the path was always absolute. To preserve the old behavior, enable the classic compatible mode in the `Configuration` object.

Always use `/` (slash) to separate path components, never `\` (backslash). If you are loading templates from your local file system and it uses backslashes (like under. Windows), FreeMarker will convert them automatically.

Example:

Assume /common/copyright.ftl contains:

    Copyright 2001-2002 ${me}<br>
    All rights reserved.

Then this:

    <#assign me = "Juila Smith">
    <h1>Some test</h1>
    <p>Yeah.
    <hr>
    <#include "/common/copyright.ftl">

will output this:

    <h1>Some test</h1>
    <p>Yeah.
    <hr>
    Copyright 2001-2002 Juila Smith
    All rights reserved.

The supported `options` are:

- parse: If it is true, then the included file will be parsed as FTL, otherwise the whole file will be considered as simple text (i.e, no FreeMarker constructs will be searched in it). If you omit this option, then it defaults to true.

- encoding: The included file inherits the encoding (in practice: the charset) of the including template, unless you specify an encoding with this option. Encoding names are the same as the ones supported be java.io.InputStreamReader (as of Java API 1.3: MIME-preferred charset names from the IANA Charset Registry). Examples of valid names: ISO-8859-2, UTF-8, Shift_JIS, Big5, EUC-KR, GB2312.

Example:

    <#include "/common/navbar.html" parse=false encoding="Shift_JIS">

Note, that it is possible to automatically do the commonly used inclusions for all templates, with the "auto includes" setting of `Configuration`.

###### Using acquisition

There's a special path component represented by an asterisk (`*`). It is interpreted as "this directory or any of its parents". Therefore, if the template located in `/foo/bar/template.ftl` has the following line:

    <#include "*/footer.ftl">

then the engine will look for the template in following locations, in this order:

- `/foo/bar/footer.ftl`

- `/foo/footer.ftl`

- `/footer.ftl`

This mechanism is called acquisition and allows the designers to place commonly included files in a parent directory, and redefine them on a per-subdirectory basis as needed. We say that the including template acquires the template to include from the first parent directory that has it. Note that you can specify not only a template name to the right of the asterisk, but a subpath as well. I.e. if the previous template instead read:

    <#include "*/commons/footer.ftl">

then the engine would look for the template in following locations, in this order:

- `/foo/bar/commons/footer.ftl`

- `/foo/commons/footer.ftl`

- `/commons/footer.ftl`

Finally, the asterisk needn't be the first element of the path:

    <#include "commons/*/footer.ftl">

would cause the engine to look for the template in following locations, in this order:

- `/foo/bar/commons/footer.ftl`

- `/foo/bar/footer.ftl`

- `/foo/footer.ftl`

- `/footer.ftl`

However, there can be at most one asterisk in the path. Specifying more than one asterisk will result in a template not being found.

acquisition

###### Localized lookup

Whenever a template is loaded, it is assigned a locale. A locale is a language and an optional country or dialect identifier. A template is typically loaded by some code that the programmer wrote and he chooses a locale for the template based on some aspect. For example, when the `FreemarkerServlet` loads templates, it always requests the template with locale matching the language preference of the browser that requested the web page.

When a template includes another template, it attempts to load a template with the same locale. Suppose your template was loaded with locale `en_US`, which means U.S. English. When you include another template:

    <include "footer.ftl">

the engine will in fact look for several templates, in this order:

- `footer_en_US.ftl`,

- `footer_en.ftl`, and finally

- `footer.ftl`

Note that you can disable localized lookup feature with the `setLocalizedLookup` method of `Configuration`.

When you use both acquisition and localized template lookup, the template with more specific locale in a parent directory takes precedence over template with less specific locale in a child directory. Suppose you use the following include from `/foo/bar/template.ftl`:

    <#include "*/footer.ftl">

the engine will look for these templates, in this order:

- `/foo/bar/footer_en_US.ftl`

- `/foo/footer_en_US.ftl`

- `/footer_en_US.ftl`

- `/foo/bar/footer_en.ftl`

- `/foo/footer_en.ftl`

- `/footer_en.ftl`

- `/foo/bar/footer.ftl`

- `/foo/footer.ftl`

- `/footer.ftl`

localization
include directive

#### import

##### Synopsis

    <#import path as hash>

Where:

- `path`: The path of a template. This is an expression that evaluates to a string. (With other words, it doesn't have to be a fixed string, it can also be something like, for example, `profile.baseDir + "/menu.ftl"`.)

- `hash`: The unquoted name of hash variable by which you can access the namespace. Not an expression.

##### Description

Imports a library. That is, it creates a new empty namespace, and then executes the template given with `path` parameter in that namespace so the template populates the namespace with variables (macros, functions, ...etc.). Then it makes the newly created namespace available to the caller with a hash variable. The hash variable will be created as a plain variable in the namespace used by the caller of `import` (as if you would create it with `assign` directive), with the name given with the `hash` parameter.

If you call `import` with the same `path` for multiple times, it will create the namespace and run the template for the very first call of `import` only. The later calls will just create a hash by which you can access the same namespace.

The output printed by the imported template will be ignored (will not be inserted at the place of importing). The template is executed to populate the namespace with variables, and not to write to the output.

Example:

    <#import "/libs/mylib.ftl" as my>

    <@my.copyright date="1999-2002"/>

The `path` parameter can be a relative path like `"foo.ftl"` and `"../foo.ftl"`, or an absolute like `"/foo.ftl"`. Relative paths are relative to the directory of the template that uses the `import` directive. Absolute paths are relative to a base (often referred as the ''root directory of the templates'') that the programmer defines when he configures FreeMarker.

Always use `/` (slash) to separate path components, never `\` (backslash). If you are loading templates from your local file system and it uses backslashes (like under. Windows), FreeMarker will convert them automatically.

Like with the `include` directive, acquisition and localized lookup may be used for resolving the path.

Note, that it is possible to automatically do the commonly used imports for all templates, with the "auto imports" setting of `Configuration`.

If you are new to namespaces, you should read:

import directive

#### noparse

##### Synopsis

    <#noparse>
      ...
    </#noparse>

##### Description

FreeMarker will not search FTL tags and interpolations and other special character sequences in the body of this directive, except the noparse end-tag.

Example:

    Example:
    --------

    <#noparse>
      <#list animals as being>
      <tr><td>${being.name}<td>${being.price} Euros
      </#list>
    </#noparse>

will output:

    Example:
    --------

      <#list animals as being>
      <tr><td>${being.name}<td>${being.price} Euros
      </#list>

noparse directive

#### compress

##### Synopsis

    <#compress>
      ...
    </#compress>

##### Description

The compress directive is useful for removing superfluous white-space when you use a white-space insensitive format (e.g. HTML or XML). It captures the output generated inside its body (i.e. between its start-tag and end-tag), and reduces all unbroken white-space sequences to a single white-space character. The inserted character will be a line break if the replaced sequence contains line breaks, or a space otherwise. The very first and very last unbroken white-space sequences will be completely removed.

    <#assign x = "    moo  \n\n   ">
    (<#compress>
      1 2  3   4    5
      ${moo}
      test only

      I said, test only

    </#compress>)

will output:

    (1 2 3 4 5
    moo
    test only
    I said, test only)

compress directive
white-space removal compress

#### escape, noescape

##### Synopsis

    <#escape identifier as expression>
      ...
      <#noescape>...</#noescape>
      ...
    </#escape>

##### Description

When you surround a part of the template with an escape directive, interpolations (`${...}`) that occur inside the block are combined with the escaping expression automatically. This is a convenience method for avoiding writing similar expressions all over. It does not affect interpolations in string literals (as in `<#assign x = "Hello ${user}!">`). Also, it does not affect numerical interpolations (`#{...}`).

Example:

    <#escape x as x?html>
      First name: ${firstName}
      Last name: ${lastName}
      Maiden name: ${maidenName}
    </#escape>

is actually equivalent to:

      First name: ${firstName?html}
      Last name: ${lastName?html}
      Maiden name: ${maidenName?html}

Note that it is irrelevant what identifier you use in the directive - it just serves as a formal parameter to the escaping expression.

When you are calling macros or the `include` directive, it is important to understand that escape has effect only on interpolations that occur between the `<#escape ...>` and `</#escape>` in the template text. That is, it will not escape anything that is before `<#escape ...>` in the text, or after the `</#escape>` in the text, not even if that part is called from inside the `escape`-d section.

    <#assign x = "<test>">
    <#macro m1>
      m1: ${x}
    </#macro>
    <#escape x as x?html>
      <#macro m2>m2: ${x}</#macro>
      ${x}
      <@m1/>
    </#escape>
    ${x}
    <@m2/>

the output will be:

      &lt;test&gt;
      m1: <test>
    <test>
    m2: &lt;test&gt;

More technically, the effects of `escape` directive are applied at template parsing time rather than at template processing time. This means that if you call a macro or include another template from within an escape block, it won't affect the interpolations in the macro/included template, since macro calls and template includes are evaluated at template processing time. On the other hand, if you surround one or more macro declarations (which are evaluated at template parsing time, as opposed to macro calls) with an escape block, the interpolations in those macros will be combined with the escaping expression.

Sometimes there is a need to temporarily turn off escaping for one or two interpolations in an escape block. You can achieve this by closing and later reopening the escape block, but then you have to write the escaping expression twice. You can instead use the noescape directive:

    <#escape x as x?html>
      From: ${mailMessage.From}
      Subject: ${mailMessage.Subject}
      <#noescape>Message: ${mailMessage.htmlFormattedBody}</#noescape>
      ...
    </#escape>

is equivalent to:

      From: ${mailMessage.From?html}
      Subject: ${mailMessage.Subject?html}
      Message: ${mailMessage.htmlFormattedBody}
      ...

Escapes can be nested (although you will do it only in rare circumstances). Therefore, you can write something like the below code (the example is admittedly a bit stretched, as you'd probably place item codes in a sequence and use `list` to iterate over them, but we're now doing it this way just to illustrate the point):

    <#escape x as x?html>
      Customer Name: ${customerName}
      Items to ship:
      <#escape x as itemCodeToNameMap[x]>
        ${itemCode1}
        ${itemCode2}
        ${itemCode3}
        ${itemCode4}
      </#escape>
    </#escape>

is actually equivalent to:

      Customer Name: ${customerName?html}
      Items to ship:
        ${itemCodeToNameMap[itemCode1]?html}
        ${itemCodeToNameMap[itemCode2]?html}
        ${itemCodeToNameMap[itemCode3]?html}
        ${itemCodeToNameMap[itemCode4]?html}

When you use the noescape directive in a nested escape block, it undoes only a single level of escaping. Therefore, to completely turn off escaping in a two-level deep escaped block, you need to use two nested noescape directives as well.

escape directive
noescape directive

#### assign

##### Synopsis

    <#assign name=value>
    or
    <#assign name1=value1 name2=value2 ... nameN=valueN>
    or
    <#assign same as above... in namespacehash>
    or
    <#assign name>
      capture this
    </#assign>
    or
    <#assign name in namespacehash>
      capture this
    </#assign>

Where:

- `name`: name of the variable. It is not expression. However, it can be written as a string literal, which is useful if the variable name contains reserved characters, for example `<#assign "foo-bar" = 1>`. Note that this string literal does not expand interpolations (as `"${foo}"`).

- `value`: the value to store. Expression.

- `namespacehash`: a hash that was created for a namespace (by `import`). Expression.

##### Description

With this you can create a new variable, or replace an existing variable. Note that only top-level variables can be created/replaced (i.e. you can't create/replace `some_hash.subvar`, but `some_hash`).

For more information about variables, read this:

Example: variable `seasons` will store a sequence:

    <#assign seasons = ["winter", "spring", "summer", "autumn"]>

Example: Increments the numerical value stored in variable `test`:

    <#assign test = test + 1>

As a convenience feature, you can do more assignments with one `assign` tag. For example this will do the same as the two previous examples:

    <#assign
      seasons = ["winter", "spring", "summer", "autumn"]
      test = test + 1
    >

If you know what namespaces are: `assign` directive creates variables in namespaces. Normally it creates the variable in the current namespace (i.e. in the namespace associated with the template where the tag is). However, if you use `in namespacehash` then you can create/replace a variable of another namespace than the current namespace. For example, here you create/replace variable `bgColor` of the namespace used for `/mylib.ftl`:

    <#import "/mylib.ftl" as my>
    <#assign bgColor="red" in my>

An extreme usage of `assign` is when it captures the output generated between its start-tag and end-tag. That is, things that are printed between the tags will not be shown on the page, but will be stored in the variable. For example:

    <#macro myMacro>foo</#macro>
    <#assign x>
      <#list 1..3 as n>
        ${n} <@myMacro />
      </#list>
    </#assign>
    Number of words: ${x?word_list?size}
    ${x}

will print:

    Number of words: 6
        1 foo
        2 foo
        3 foo

Please note that you should not to use this to insert variables into strings:

    <#assign x>Hello ${user}!</#assign> <#-- BAD PRACTICE! -->

You should simply write:

    <#assign x="Hello ${user}!">

assign directive

#### global

##### Synopsis

    <#global name=value>
    or
    <#global name1=value1 name2=value2 ... nameN=valueN>
    or
    <#global name>
      capture this
    </#global>

Where:

- `name`: name of the variable. It is not expression. However, it can be written as a string literal, which is useful if the variable name contains reserved characters, for example `<#global "foo-bar" = 1>`. Note that this string literal does not expand interpolations (as `"${foo}"`).

- `value`: the value to store. Expression.

##### Description

This directive is similar to `assign`, but the variable created will be visible in all namespaces, and will not be inside any namespace. Exactly as if you would create (or replace) a variable of the data-model. Hence, the variable is global. If a variable with the same name already exists in the data-model, it will be hidden by the variable created with this directive. If a variable with the same name already exists in the current namespace, that will hide the variable created with `global` directive.

For example, with `<#global x = 1>` you create a variable that is visible as `x` in all namespaces, unless another variable called `x` hides it (for example a variable what you have created as `<#assign x = 2>`). In this case, you can use special variable `globals`, like `${.globals.x}`. Note that with `globals` you see all globally accessible variables; not only the variables that were created with `global` directive, but also the variables of the data-model.

Note for custom JSP tag users: The set of variables created with this directive corresponds to the JSP page-scope. This means, that if a custom JSP tag wants to get a page-scope attribute (page-scope bean), a variable with the same name in the current namespace will not hide it from the viewpoint of the JSP tag.

global directive

#### local

##### Synopsis

    <#local name=value>
    or
    <#local name1=value1 name2=value2 ... nameN=valueN>
    or
    <#local name>
      capture this
    </#local>

Where:

- `name`: the name of the local object in the root. It is not an expression. However, it can be written as a string literal, which is useful if the variable name contains reserved characters, for example `<#local "foo-bar" = 1>`. Note that this string literal does not expand interpolations (as `"${foo}"`).

- `value`: the value to store. Expression.

##### Description

It is similar to assign directive, but it creates or replaces local variables. This only works inside macro definitions and function definitons.

For more information about variables, read this:

local directive

#### setting

##### Synopsis

    <#setting name=value>

Where:

- `name`: name of the setting. It is not expression!

- `value`: New value of the setting. Expression

##### Description

Sets a setting for the further part of processing. Settings are values that influence the behavior of FreeMarker. The new value will be present only in the template processing where it was set, and does not touch the template itself. The initial value of settings is set by the programmer (see: ).

The supported settings are:

- `locale`: The locale (language) of the output. It can influence the presentation format of numbers, dates, etc. The value is a string which consist of a language code (lowercase two-letter ISO-639 code) plus optional county code (uppercase two-letter ISO-3166 code) separated from the language code with underscore, and if we have specified the country then an optional variant code (not standardized) separated from the country with underscore. Examples of valid values: `en`, `en_US`, `en_US_MAC`. FreeMarker will try to use the most specific available locale, so if you specify `en_US_MAC` but that is not known, then it will try `en_US`, and then `en`, and then the default locale of the computer (which is may set by the programmer).

  locale

- `number_format`: The number format that is used to convert numbers to strings when no explicit format is specified. Can be one of predefined values `number` (the default), `computer`, `currency`, or `percent`. Additionally, arbitrary format pattern written in Java decimal number format syntax can also be specified. More information about format patterns:`string` built-in.

  number_format
  format number

- `boolean_format`: The comma-separated pair of strings for representing true and false values respectively that is used to convert booleans to strings when no explicit format is specified. Default value is `"true,false"`. See also:`string` built-in.

  boolean_format
  format boolean

- `date_format`, `time_format`, `datetime_format`: The date/time format used to convert dates to strings when no explicit format is specified, as in the case of `${someDate}`. `date_format` affects only the formatting of date-only dates (year, month, day), `time_format` affects only the formatting of time-only dates (hour,minute, second, millisecond), `datetime_format` affects only the formatting of date-time dates (year, month, day, hour, minute, second, millisecond). The possible values of the settings are similar to the parameters of `string` built-in of dates; see more explanation there. Examples: `"short"`, `"long_medium"`, `"MM/dd/yyyy"`.

  date_format
  time_format
  datetime_format
  format date

- `time_zone`: The name of the time zone used to format times for display. By default, the system time zone is used. Can be any value that is accepted by Java TimeZone API. Examples: `"GMT"`, `"GMT+2"`, `"GMT-1:30"`, `"CET"`, `"PST"`, `"America/Los_Angeles"`

  time_zone

- `url_escaping_charset`: The charset used for URL escaping (e.g. for `${foo?url}`) to calculate the escaped (`%XX`) parts. Usually the framework that encloses FreeMarker should set it, so you hardly ever should set this setting in templates. (Programmers can read more about this here...)

  url_escaping_charset

- `classic_compatible`: This is for experts. Its value should be a boolean. See the documentation of `freemarker.template.Configurable` for more information.

  classic_compatible

Example: Assume that the initial locale of template is hu (Hungarian). Then this:

    ${1.2}
    <#setting locale="en_US">
    ${1.2}

will output this:

    1,2
    1.2

because Hungarian people use the comma as their decimal separator, while US people use the dot.

setting directive

#### User-defined directive (<@...>)

##### Synopsis

    <@user_def_dir_exp param1=val1 param2=val2 ... paramN=valN/>
    (Note the XML-style / before the >)
    or if you need loop variables (more details...)
    <@user_def_dir_exp param1=val1 param2=val2 ... paramN=valN ; lv1, lv2, ..., lvN/>

    Or the same as the above two but with end-tag (more details...):

    <@user_def_dir_exp ...>
      ...
    </@user_def_dir_exp>
    or
    <@user_def_dir_exp ...>
      ...
    </@>

    Or all above but with positional parameter passing (more details...):

    <@user val1, val2, ..., valN/>
    ...etc.

Where:

- `user_def_dir_exp`: Expression evaluates to an user-defined directive (for example a macro), that will be called.

- `param1`, `param2`, ...etc.: The name of parameters. They are not expressions.

- `val1`, `val2`, ...etc.: The value of parameters. They are expressions.

- `lv1`, `lv2`, ...etc.: The name of loop variables. They are not expressions.

The number of parameters can be 0 (i.e. no parameters).

The order of parameters is not significant (unless you use positional parameter passing). The name of parameters must be unique. Lower- and uppercase letters are considered as different letters in parameter names (i.e. `Color` and `color` is not the same).

##### Description

This will call an user-defined directive, for example a macro. The meaning of parameters, and the set of supported and required parameters depend on the concrete user-defined directive.

You may read the tutorial about user-defined directives.

Example 1: Calls the directive that is stored in the variable `html_escape`:

    <@html_escape>
      a < b
      Romeo & Juliet
    </@html_escape>

Output:

      a &lt; b
      Romeo &amp; Juliet

Example 2: Calls a macro with parameters:

    <@list items=["mouse", "elephant", "python"] title="Animals"/>
    ...
    <#macro list title items>
      <p>${title?cap_first}:
      <ul>
        <#list items as x>
          <li>${x?cap_first}
        </#list>
      </ul>
    </#macro>

Output:

      <p>Animals:
      <ul>
          <li>Mouse
          <li>Elephant
          <li>Python
      </ul>

    ...

###### End-tag

You can omit the `user_def_dir_exp` in the end-tag. That is, you can always write `</@>` instead of `</@anything>`. This rule is mostly useful when the `user_def_dir_exp` expression is too complex, because you don't have to repeat the expression in the end-tag. Furthermore, if the expression contains other than simple variable names and dots, you are not allowed to repeat the expression. For example, `<@a_hash[a_method()]>...</@a_hash[a_method()]>` is an error; you must write `<@a_hash[a_method()]>...</@>`. But `<@a_hash.foo>...</@a_hash.foo>` is OK.

###### Loop variables

Some user-defined directives create loop variables (similarly to `list` directive). As with the predefined directives (as `list`) the name of loop variables is given when you call the directive (as `foo` in `<#list foos as foo>...</#list>`), while the value of the variable is set by the directive itself. In the case of user-defined directives the syntax is that the name of loop variables is given after a semicolon. For example:

    <@myRepeatMacro count=4 ; x, last>
      ${x}. Something... <#if last> This was the last!</#if>
    </@myRepeatMacro>

Note that the number of loop variable created by the user-defined directive and the number of loop variables specified after the semicolon need not match. Say, if you are not interested if the repetition is the last, you can simply write:

    <@myRepeatMacro count=4 ; x>
      ${x}. Something...
    </@myRepeatMacro>

or you can even:

    <@myRepeatMacro count=4>
      Something...
    </@myRepeatMacro>

Furthermore, it does not cause error if you specify more loop variables after the semicolon than the user-defined directive creates, just the last few loop variables will not be created (i.e. those will be undefined in the nested content). Trying to use the undefined loop variables, however, will cause error (unless you use built-ins like `?default`), since you try to access a non-existing variable.

See the the tutorial about user-defined directives for more explanation.

###### Positional parameter passing

Positional parameter passing (as `<@heading "Preface", 1/>`) is a shorthand form of normal named parameter passing (as `<@heading title="Preface" level=1/>`), where you omit the parameter name. This shorthand form should be used if a user-defined directive has only one parameter, or if it is easy to remember the order of parameters for a frequently used user-defined directive. To use this form, you have to know the order in which the named parameters are declared (trivial if the directive has only one parameter). Say, if `heading` was created as `<#macro heading title level>...`, then `<@heading "Preface", 1/>` is equivalent with `<@heading title="Preface" level=1/>` (or `<@heading level=1 title="Preface"/>`; if you use parameter names, the order is not important). Note that positional parameter passing is currently only supported for macros.

positional parameter passing
user-defined directive

#### macro, nested, return

##### Synopsis

    <#macro name param1 param2 ... paramN>
      ...
      <#nested loopvar1, loopvar2, ..., loopvarN>
      ...
      <#return>
      ...
    </#macro>

Where:

- `name`: name of macro variable. It's not an expression. However, it can be written as a string literal, which is useful if the macro name contains reserved characters, for example `<#macro "foo-bar">...`. Note that this string literal does not expand interpolations (as `"${foo}"`).

- `param1`, `param2`, ...etc.: the name of the local variables store the parameter values (not expression), optionally followed by `=` and the default value (that's an expression). The default value can even be another parameter, for example `<#macro section title label=title>`.

- `paramN`, the last parameter, may optionally include a trailing ellipsis (`...`), which indicates the macro takes a variable number of parameters. If called using named parameters, `paramN` will be a hash containing all of the undeclared key/value pairs passed to the macro. If called using positional parameters, `paramN` will be a sequence of the extra parameters.

- `loopvar1`, `loopvar2`, ...etc.: Optional. The values of loop variables that the `nested` directive wants to create for the nested content. These are expressions.

The `return` and `nested` directives are optional and can be used anywhere and for any times between the `<#macro ...>` and `</#macro>`.

Parameters without default value must precede parameters with default value (`paramName=defaultValue`).

##### Description

Creates a macro variable (in the current namespace, if you know namespace feature). If you are new to macros and user-defined directives you should read the the tutorial about user-defined directives.

Macro variable stores a template fragment (called macro definition body) that can be used as user-defined directive. The variable also stores the name of allowed parameters to the user-defined directive. You must give value for all of those parameters when you use the variable as directive, except for parameters that has a default value. The default value will be used if and only if you don't give value for the parameter when you call the macro.

The variable will be created at the beginning of the template; it does not mater where the `macro` directive is placed in the template. Thus, this will work:

    <#-- call the macro; the macro variable is already created: -->
    <@test/>
    ...

    <#-- create the macro variable: -->
    <#macro test>
      Test text
    </#macro>

However, if the macro definitions are inserted with `include` directive, they will not be available until FreeMarker has executed the `include` directive.

Example: Macro without parameters:

    <#macro test>
      Test text
    </#macro>
    <#-- call the macro: -->
    <@test/>

Output:

      Test text

Example: Macro with parameters:

    <#macro test foo bar baaz>
      Test text, and the params: ${foo}, ${bar}, ${baaz}
    </#macro>
    <#-- call the macro: -->
    <@test foo="a" bar="b" baaz=5*5-2/>

Output:

      Test text, and the params: a, b, 23

Example: Macro with parameters and default parameter values:

    <#macro test foo bar="Bar" baaz=-1>
      Test text, and the params: ${foo}, ${bar}, ${baaz}
    </#macro>
    <@test foo="a" bar="b" baaz=5*5-2/>
    <@test foo="a" bar="b"/>
    <@test foo="a" baaz=5*5-2/>
    <@test foo="a"/>

Output:

      Test text, and the params: a, b, 23
      Test text, and the params: a, b, -1
      Test text, and the params: a, Bar, 23
      Test text, and the params: a, Bar, -1

Example: A more complex macro.

    <#macro list title items>
      <p>${title?cap_first}:
      <ul>
        <#list items as x>
          <li>${x?cap_first}
        </#list>
      </ul>
    </#macro>
    <@list items=["mouse", "elephant", "python"] title="Animals"/>

Output:

      <p>Animals:
      <ul>
          <li>Mouse
          <li>Elephant
          <li>Python
      </ul>

Example: A macro with support for a variable number of named parameters:

    <#macro img src extra...>
      <img src="/context${src?html}"
      <#list extra?keys as attr>
        ${attr}="${extra[attr]?html}"
      </#list>
      >
    </#macro>
    <@img src="/images/test.png" width=100 height=50 alt="Test"/>

Output:

      <img src="/context/images/test.png"
        alt="Test"
        height="50"
        width="100"
      >

###### nested

The `nested` directive executes the template fragment between the start-tag and end-tags of the user-defined directive. The nested part can contain anything what is valid in templates; interpolations, directives, ...etc. It is executed in the context where the macro was called from, rather than in the context of the macro definition body. Thus, for example, you don't see the local variables of the macro in the nested part. If you don't call the `nested` directive, the part between the start-tag and end-tags of the user-defined directive will be ignored.

Example:

    <#macro do_twice>
      1. <#nested>
      2. <#nested>
    </#macro>
    <@do_twice>something</@do_twice>

Output:

      1. something
      2. something

The nested directive can create loop variables for the nested content. For example:

    <#macro do_thrice>
      <#nested 1>
      <#nested 2>
      <#nested 3>
    </#macro>
    <@do_thrice ; x>
      ${x} Anything.
    </@do_thrice>

This will print:

      1 Anything.
      2 Anything.
      3 Anything.

A more complex example:

    <#macro repeat count>
      <#list 1..count as x>
        <#nested x, x/2, x==count>
      </#list>
    </#macro>
    <@repeat count=4 ; c, halfc, last>
      ${c}. ${halfc}<#if last> Last!</#if>
    </@repeat>

The output will be:

      1. 0.5
      2. 1
      3. 1.5
      4. 2 Last!

###### return

With the `return` directive, you can leave a macro or function definition body anywhere. Example:

    <#macro test>
      Test text
      <#return>
      Will not be printed.
    </#macro>
    <@test/>

Output:

      Test text

macro directive
nested directive
return directive

#### function, return

##### Synopsis

    <#function name param1 param2 ... paramN>
      ...
      <#return returnValue>
      ...
    </#function>

Where:

- `name`: name of method variable (not expression)

- `param1`, `param2`, ...etc.: the name of the local variables store the parameter values (not expression), optionally followed by `=` and the default value (that's an expression).

- `paramN`, the last parameter, may optionally include a trailing ellipsis (`...`), which indicates the macro takes a variable number of parameters. Local variable `paramN` will be a sequence of the extra parameters.

- `returnValue`: the expression that calculates the value of the method call.

The `return` directive can be used anywhere and for any times between the `<#function ...>` and `</#function>`.

Parameters without default value must precede parameters with default value (`paramName=defaultValue`).

##### Description

Creates a method variable (in the current namespace, if you know namespace feature). This directive works in the same way as the `macro` directive, except that `return` directive must have a parameter that specifies the return value of the method, and that attempts to write to the output will be ignored. If the `</#function>` is reached (i.e. there was no `return returnValue`), then the return value of the method is an undefined variable.

Example 1: Creating a method that calculates the average of two numbers:

    <#function avg x y>
      <#return (x + y) / 2>
    </#function>
    ${avg(10, 20)}

will print:

    15

Example 2: Creating a method that calculates the average of multiple numbers:

    <#function avg nums...>
      <#local sum = 0>
      <#list nums as num>
        <#local sum = sum + num>
      </#list>
      <#if nums?size != 0>
        <#return sum / nums?size>
      </#if>
    </#function>
    ${avg(10, 20)}
    ${avg(10, 20, 30, 40)}
    ${avg()!"N/A"}

will print:

    15
    25
    N/A

function directive
return directive
method defining with FTL

#### flush

##### Synopsis

    <#flush>

##### Description

When FreeMarker generates the output it typically stockpiles the generated output and send it to the client in one or in a few big pieces. This act of sending is called flushing (as flushing the toilet). Although flushing happens automatically, sometimes you want to force it on certain points of the template processing, and this is what `flush` directive does. If it is needed, then the programmer could tell it to you; typically you should not use this directive. The mechanism of automatic flushing and the precise effect of `flush` directive are under the control of the programmer.

Flush simply calls the flush method of the currently used java.io.Writer instance. The whole buffering and flushing mechanism is implemented in the writer (what you have passed as the parameter of the `Template.process` method); FreeMarker does not deal with it.

flush directive

#### stop

##### Synopsis

    <#stop>
    or
    <#stop reason>

Where:

- `reason`: Informative message about the reason of termination. Expression evaluates to string.

##### Description

Aborts the processing of template. This is something like an emergency brake: don't use it in normal situations. Aborting happens by throwing a `StopException`, and the `StopException` will hold the value of reason parameter.

stop directive

#### ftl

##### Synopsis

    <#ftl param1=value1 param2=value2 ... paramN=valueN>

Where:

- `param1`, `param2`, ...etc.: Name of the parameter. Not an expression. Allowed parameters are: `encoding`, `strip_whitespace`, `strip_text`, ...etc. See below.

- `value1`, `value2`, ...etc.: The value of parameter. This must be a constant expression (as `true`, or `"ISO-8859-5"`, or `{x:1, y:2}`). It can't use variables.

##### Description

Tells information about the template for FreeMarker and for other tools, also helps programs to automatically detect if a text file is an FTL file. This directive, if present, must be the very first thing in the template. Any white-space before this directive will be ignored. The old-syntax (`#`-less) format of this directive is not supported.

The settings (encoding, white-space stripping, etc.) given here has the highest precedence, that is, they will be used for the template regardless of any FreeMarker configuration settings.

Parameters:

- `encoding`: With this you can specify the encoding (charset) of the template in the template file itself. (That is, this will be the `encoding` setting of the newly created `Template`, and not even the `encoding` parameter to `Configuration.getTemplate` can override it). Note however, that FreeMarker will try to find and interpret the `ftl` directive first with the automatically guessed encoding (which depends on the FreeMarker configuration set by the programmers), and only then realizes if the `ftl` directive dictates something different, and re-read the template with the new encoding. Thus, the template must be valid FTL until the end of `ftl` tag with the encoding tried first. The valid values of this parameter are MIME-preferred charset names from the IANA Charset Registry, like ISO-8859-5, UTF-8 or Shift_JIS.

- `strip_whitespace`: This enables/disables white-space stripping. Valid values are the boolean constants `true` and `false`. (And for backward compatibility, strings `"yes"`, `"no"`, `"true"`, `"false"`). The default value (i.e. when you don't use this parameter) depends on the FreeMarker configuration set by the programmers, but it should be `true` for new projects.

- `strip_text`: When enabled, all top-level text in a template is removed when the template is parsed. This does not affect text within macros, directives, or interpolations. Valid values are the boolean constants `true` and `false`. (And for backward compatibility, strings `"yes"`, `"no"`, `"true"`, `"false"`). The default value (i.e. when you don't use this parameter) is `false`.

- `strict_syntax`: This turns on/off ``strict syntax''. Valid values are the boolean constants `true` and `false`. (And for backward compatibility, strings `"yes"`, `"no"`, `"true"`, `"false"`). The default value (i.e. when you don't use this parameter) depends on the FreeMarker configuration set by the programmers, but it should be `true` for new projects. (Programmers: you must set explicitly this setting to `true` for this: `config.setStrictSyntaxMode(true);`) For more information read:

- `ns_prefixes`: This is a hash that associates prefixes with node namespaces. For example: `{"e":"http://example.com/ebook", "vg":"http://example.com/vektorGraphics"}`. This is mostly used with XML processing where the prefixes can be used in XML queries, but it also influences the working of directives `visit` and `recurse`. Only one prefix can be registered for the same node namespace (otherwise an error will occur), so there is one-to-one relation between prefixes and node namespaces. Prefixes `D` and `N` are reserved. If you register prefix `D`, then other than you associate the node namespace with prefix `D`, you also set the default node namespace. Prefix `N` can't be registered; it is used to denote nodes with no node namespace in certain places, when (and only when) prefix `D` is registered. (To see the usage of default node namespace, `N`, and prefixes in general, see the part about XML processing and `visit` and `recurse` in the reference.) The effect of `ns_prefixes` is limited to a single FTL namespace, namely, to the FTL namespace that was created for the template. This also means that `ns_prefixes` has effect only when an FTL namespace is created for the template that contains it, otherwise the `ns_prefixes` parameter has no effect. An FTL namespace is made for a template when: (a) the template is the ``main'' template, that is, it is not invoked as a result of an `<#include ...>`, but it is directly invoked (with the `process` Java method of class `Template` or `Environment`); (b) the template is invoked directly with `<#import ...>`.

- `attributes`: This is a hash that associates arbitrary attributes (name-value pairs) to the template. The values of the attributes can be of any type (string, number, sequence... etc.). FreeMarker doesn't try to understand the meaning of the attributes. It's up to the application that encapsulates FreeMarker (as a Web application framework). Thus, the set of allowed attributes and their semantic is application (Web application framework) dependent. Programmers: you can get the attributes associated with a `Template` object with its `getCustomAttributeNames` and `getCustomAttribute` methods (inherited from `freemarker.core.Configurable`). As the template attributes are associated with the `Template` object when the template is parsed, the attributes can be read anytime, the template need not be executed. The methods mentioned return the attribute values unwrapped, that is, with FreeMarker independent type as `java.util.List`.

This directive also determines if the template uses angle bracket syntax (e.g. `<#include 'foo.ftl'>`) or square bracket syntax (e.g. `[#include 'foo.ftl']`). Simply, the syntax used for this directive will be the syntax used for the whole template, regardless of the FreeMarker configuration settings.

ftl directive
header
charset
encoding
white-space removal stripping

#### t, lt, rt

##### Synopsis

    <#t>

    <#lt>

    <#rt>

    <#nt>

##### Description

These directives, instruct FreeMarker to ignore certain white-space in the line of the tag:

- `t` (for trim): Ignore all leading and trailing white-space in this line.

- `lt` (for left trim): Ignore all leading white-space in this line.

- `rt` (for right trim): Ignore all trailing white-space in this line.

where:

- ``leading white-space'' means all space and tab (and other character that are white-space according to UNICODE, except line breaks) before the first non-white-space character of the line.

- ``trailing white-space'' means all space and tab (and other character that are white-space according to UNICODE, except line breaks) after the last non-white-space character of the line, and the line break at the end of the line.

It is important to understand that these directives examine the template itself, and not the output what the template generates when you merge it with the data-model. (That is, the white-space removal happens on parse time.)

For example this:

    --
      1 <#t>
      2<#t>
      3<#lt>
      4
      5<#rt>
      6
    --

will output this:

    --
    1 23
      4
      5  6
    --

The placement of these directives inside the line has no importance. That is, the effect will be the same regardless if you put the directive at the beginning of the line, or at the end of the line, or in the middle of the line.

t directive
lt directive
rt directive
trimmer directives
white-space removal trimming

#### nt

##### Synopsis

    <#nt>

##### Description

``No Trim''. This directive disables white-space stripping in the line where it occurs. It also disables the effect of other trim directives occuring in the same line (the effect of `t`, `rt`, `lt`).

nt directive
trimmer directives
white-space removal trimming
white-space removal stripping

#### attempt, recover

##### Synopsis

    <#attempt>
      attempt block
    <#recover>
      recover block
    </#attempt>

Where:

- `attempt block`: Template block with any content. This will be always executed, but if an error occurs during that, all output from this block is rolled back, and the `recover block` will be executed.

- `recover block`: Template block with any content. This will be executed only if there was an error during the execution of the `attempt block`. You may print an error messages here and such.

The `recover` is mandatory. `attempt`/`recover` can be nested freely into other `attempt block`s or `recover block`s.

The format shown here is supported starting from 2.3.3; earlier it was `<#attempt>...<#recover>...</#recover>`, which is still supported for backward compatibility. Furthermore, these directives were introduced with FreeMarker 2.3.1, so they aren't exist in 2.3.

##### Description

These directives are used if you want the page successfully outputted even if the outputting of a certain part of the page fails. If an error occurs during the execution of the `attempt block`, then the template execution is not aborted, but the `recover block` is executed instead of the `attempt block`. If no error occurs during the execution of the `attempt block`, then the `recover block` is ignored. A simple example:

    Primary content
    <#attempt>
      Optional content: ${thisMayFails}
    <#recover>
      Ops! The optional content is not available.
    </#attempt>
    Primary content continued

If the `thisMayFails` variable doesn't exist, then the output is:

    Primary content
      Ops! The optional content is not available.
    Primary content continued

If the `thisMayFails` variable exists and it's value is `123`, then the output is:

    Primary content
      Optional content: 123
    Primary content continued

The `attempt block` has an all-or-none semantic: either the entire content of the `attempt block` is output (when there was no error), or no output at all results from the execution of the `attempt block` (when there was an error). For example, above, the failure happens after ``Optional content: '' was printed, still it is not there in the output before the ``Ops!''. (This is implemented with the aggressive buffering of the output inside the `attempt block`. Not even the `flush` directive will send the output to the client.)

To prevent misunderstandings coming from the above example: `attempt`/`recover` is not (only) for handling undefined variables (for that use missing value handler operators). It can handle all kind of errors that occurs when the block is executed (i.e. not syntactical errors, which are detected earlier). And it's meant to enclose bigger template fragments, where error can occur at various points. For example, you have a part in your template that deals with printing advertisements, but that's not the primary content of the page, so you don't want your whole page be down just because some error occurs with the printing of the advertisements (say, because of a temporal database server faliure). So you put the whole advertisement printing into an `attempt block`.

In some environments programmers configure FreeMarker so that it doesn't abort template execution for certain errors, but continues execution, possibly after printing some error indicator to the output (see more here...). The `attempt` directive doesn't consider such suppressed errors as errors.

Inside a `recover block` the error message of the error is available with the `error` special variable. Don't forget that references to special variable are started with dot (for example: `${.error}`).

Errors occurring during template execution are always logged, even if they occur inside an `attempt block`.

attempt directive
recover directive
error handling

#### visit, recurse, fallback

##### Synopsis

    <#visit node using namespace>
    or
    <#visit node>

    <#recurse node using namespace>
    or
    <#recurse node>
    or
    <#recurse using namespace>
    or
    <#recurse>

    <#fallback>

Where:

- `node`: Expression evaluates to a node variable.

- `namespace`: A namespace, or a sequence of namespaces. A namespace can be given with the namespace hash (a.k.a. gate hash), or with a string literal that store the path of template that could be imported. Instead of namespace hashes, you can use plain hashes as well.

##### Description

The `visit` and `recurse` directives are used for the recursive processing of trees. In practice, this will mostly be used for processing XML.

###### Visit

When you call `<#visit node>`, it looks for a user-defined directive (like a macro) to invoke that has the name deducted from the node's name (`node?node_name`) and namespace (`node?node_namesoace`). The rules of name deduction:

- If the node doesn't support node namespaces (as text nodes in XML), then the directive name is simply the name of the node (`node?node_name`). A node does not support node namespaces if the `getNodeNamespace` method returns `null`.

- If the node does support node namespaces (as element nodes in XML), then a prefix deduced from the node namespace maybe appended before the node name with a colon used as separator (e.g. `e:book`). The prefix, and if there is a prefix used at all, depends on what prefixes has been registered with the `ns_prefixes` parameter of the `ftl` directive in the FTL namespace where `visit` looks for the handler directive (which is not necessary the same as the FTL namespace where `visit` was called from, as you will see later). Concretely, if there was no default namespace registered with `ns_prefixes` then for nodes that does not belong to any namespace (when `getNodeNamespace` returns `""`) no prefix is used. If there was a default namespace registered with `ns_prefixes` then for nodes that does not belong to any namespace prefix `N` is used, and for nodes that belong to the default node namespace no prefix is used. Otherwise, in both case, the prefix associated to the node namespace with the `ns_prefixes` is used. If there is not prefix associated to the node namespace of the node, then `visit` simply behave as if there was no directive found with the proper name.

The node for which the user-defined directive was invoked is available for it as special variable `.node`. Example:

    <#-- Assume that nodeWithNameX?node_name is "x" -->
    <#visit nodeWithNameX>
    Done.
    <#macro x>
       Now I'm handling a node that has the name "x".
       Just to show how to access this node: this node has ${.node?children?size} children.
    </#macro>

The output will be something like:

       Now I'm handling a node that has the name "x".
       Just to show how to access this node: this node has 3 children.
    Done.

If one or more namespaces is specified using the optional `using` clause, then `visit` will look for the directives in those namespaces only, with the earlier specified namespaces in the list getting priority. If no `using` clause is specified, the namespace or sequence of namespaces specified with the `using` clause of the last uncompleted `visit` call is reused. If there is no such pending `visit` call, then the current namespace is used. For example, if you execute this template:

    <#import "n1.ftl" as n1>
    <#import "n2.ftl" as n2>

    <#-- This will call n2.x (because there is no n1.x): -->
    <#visit nodeWithNameX using [n1, n2]>

    <#-- This will call the x of the current namespace: -->
    <#visit nodeWithNameX>

    <#macro x>
      Simply x
    </#macro>

and this is `n1.ftl`:

    <#macro y>
      n1.y
    </#macro>

and this is `n2.ftl`:

    <#macro x>
      n2.x
      <#-- This will call n1.y, becuase it inherits the "using [n1, n2]" from the pending visit call: -->
      <#visit nodeWithNameY>
      <#-- This will call n2.y: -->
      <#visit nodeWithNameY using .namespace>
    </#macro>

    <#macro y>
      n2.y
    </#macro>

then this will print:

      n2.x
      n1.y
      n2.y

      Simply x

If `visit` doesn't find a user-defined directive in either FTL namespaces with the name identical to the name deduced with the rules described earlier, then it tries to find an user-defined directive with name `@node_type`, or if the node does not support node type property (i.e. `node?node_type` returns undefined variable), then with name `@default`. For the lookup, it uses the same mechanism as was explained earlier. If it still doesn't find an user-defined directive to handle the node, then `visit` stops template processing with error. Some XML specific node types have special handling in this regard; see: . Example:

    <#-- Assume that nodeWithNameX?node_name is "x" -->
    <#visit nodeWithNameX>

    <#-- Assume that nodeWithNameY?node_type is "foo" -->
    <#visit nodeWithNameY>

    <#macro x>
    Handling node x
    </#macro>

    <#macro @foo>
    There was no specific handler for node ${node?node_name}
    </#macro>

This would print:

    Handling node x

    There was no specific handler for node y

###### Recurse

The `<#recurse>` directive is really syntactic sugar. It visits all children nodes of the node (and not the node itself). So, to write:

    <#recurse someNode using someLib>

is equivalent to writing:

    <#list someNode?children as child><#visit child using someLib></#list>

However, target node is optional in the `recurse` directive. If the target node is unspecified, it simply uses the `.node`. Thus, the terse instruction `<#recurse>` is equivalent to:

    <#list .node?children as child><#visit child></#list>

As a side comment for those who are familiar with XSLT, `<#recurse>` is pretty much exactly analogous to the `<xsl:apply-templates/>` instruction in XSLT.

###### Fallback

As you could learn earlier, in the documentation of the `visit` directive, the user-defined directive that handles the node is maybe searched in multiple FTL name-spaces. The `fallback` directive can be used in a user-defined directive that was invoked to handle a node. It directs FreeMarker to continue the searching for the user-defined directive in the further name-spaces (that is, in the name-spaces that are after the name-space of the currently invoked user-defined directive in the list of name-spaces). If a handler for the node is found then it is invoked, otherwise `fallback` does nothing.

A typical usage of this to write customization layer over a handler library, that sometimes passes the handling to the customized library:

    <#import "/lib/docbook.ftl" as docbook>

    <#--
      We use the docbook library, but we override some handlers
      in this namespace.
    -->
    <#visit document using [.namespace, docbook]>

    <#--
      Override the "programlisting" handler, but only in the case if
      its "role" attribute is "java"
    -->
    <#macro programlisting>
      <#if .node.@role[0]!"" == "java">
        <#-- Do something special here... -->
        ...
      <#else>
        <#-- Just use the original (overidden) handler -->
        <#fallback>
      </#if>
    </#macro>

visit directive
recurse directive
fallback directive
recursion iterate
directive

### Special Variable Reference

Special variables are variables defined by the FreeMarker engine itself. To access them, you use the `.variable_name` syntax. For example, you can't write simply `version`; you have to write `.version`.

The supported special variables are:

- `data_model`: A hash that you can use to access the data-model directly. That is, variables you did with `global` directive are not visible here.

- `error` (available since FreeMarker 2.3.1): This variable accessible in the body of the `recover` directive, where it stores the error message of the error we recover from.

  error

- `globals`: A hash that you can use to access the globally accessible variables: the data-model and the variables created with `global` directive. Note that variables created with `assign` or `macro` are not globals, thus they never hide the variables when you use `globals`.

- `lang`: Returns the language part of the current value of the locale setting. For example if `.locale` is `en_US`, then `.lang` is `en`.

  language
  lang

- `locale`: Returns the current value of the locale setting. This is a string, for example `en_US`. For more information about locale strings see the `setting` directive.

  locale

- `locals`: A hash that you can use to access the local variables (the variables created with the `local` directive, and the parameters of macro).

- `main`: A hash that you can use to access the main namespace. Note that global variables like the variables of data-model are not visible through this hash.

- `namespace`: A hash that you can use to access the current namespace. Note that global variables like the variables of data-model are not visible through this hash.

- `node` (alias `current_node` for historical reasons): The node you are currently processing with the visitor pattern (i.e. with the `visit`, `recurse`, ...etc. directives). Also, it initially stores the root node when you use the FreeMarker XML Ant task.

- `now`: Returns the current date-time. Usage examples: "`Page generated: ${.now}`", "`Today is ${.now?date}`", "`The current time is ${.now?time}`".

  now
  current date-time

- `output_encoding` (available since FreeMarker 2.3.1): Returns the name of the current output charset. This special variable is not existent if the framework that encapsulates FreeMarker doesn't specify the output charset for FreeMarker. (Programmers can read more about charset issues here...)

  output encoding
  output charset

- `template_name`: The name of the current template (available since FreeMarker 2.3.14).

- `url_escaping_charset` (available since FreeMarker 2.3.1): If exists, it stores the name of the charset that should be used for URL escaping. If this variable doesn't exist that means that nobody has specified what charset should be used for URL encoding yet. In this case the `url` built-in uses the charset specified by the `output_encoding` special variable for URL encoding; custom mechanism may follow the same logic. (Programmers can read more about charset issues here...)

  URL escaping charset
  URL escaping charset

- `vars`: Expression `.vars.foo` returns the same variable as expression `foo`. It's useful if for some reasons you have to use square bracket syntax, since that works only for hash subvariables, so you need an artificial parent hash. For example, to read a top-level variable that has a strange name that would confuse FreeMarker, you can write `.vars["A strange name!"]`. Or, to access a top-level variable with dynamic name given with variable `varName` you can write `.vars[varName]`. Note that the hash returned by `.vars` does not support `?keys` and `?values`.

- `version`: Returns the FreeMarker version number as string, for example `2.2.8`. This can be used to check which FreeMarker version does your application use, but note that this special variable does not exist prior to the 2.3-final or 2.2.8 versions. The version number of non-final releases contain abbreviation ``pre'' for ``preview'' (e.g. `2.3pre6`), or abbrevation ``rc'' for ``release candidate''.

  version

special variable

### Reserved names in FTL

The following names cannot be used for top-level variables without square-bracket syntax (as `.vars["in"]`), since they are keywords in FTL:

- `true`: boolean value ``true''

- `false`: boolean value ``false''

- `gt`: comparison operator ``greater than''

- `gte`: comparison operator ``greater than or equivalent''

- `lt`: comparison operator ``less than''

- `lte`: comparison operator ``less than or equivalent''

- `as`: used by a few directives

- `in`: used by a few directives

- `using`: used by a few directives

reserved name

### Deprecated FTL constructs

#### List of deprecated directives

The following directives are deprecated, but still working:

- `call`: use user-defined directive call instead

- `comment`: This is the old format of `<#--...-->`. Anything between the `<#comment>` and `</#comment>` will be ignored.

- `foreach`: it is a synonym of the `list` directive with slightly different parameter syntax. The syntax is `<#foreach item in sequence>` that is equivalent with `<#list sequence as item>`.

- `transform`: use user-defined directive call instead

The following directives are not working anymore:

- Legacy `function`: Originally `function` was used to define macros, and was deprecated in favor of the `macro` directive. As of FreeMarker 2.3, this directive is reintroduced with different meaning: it is used to define methods.

#### List of deprecated built-ins

The following built-ins are deprecated, but still working:

- `default`: This was deprecated with the introduction of the default value operator. `exp1?default(exp2)` is near equivalent with `exp1!exp2`, and `(exp1)?default(exp2)` is near equivalent with with `(exp1)!exp2`. The only difference is that prior to FreeMarker 2.4, the `default` built-in has always evaluated `exp2`, while the default value operator only evaluates it when the default value is really needed. Starting from FreeMarker 2.4, however, the `default` built-in was improved, and behaves exactly like the default value operator.

  default built-in

- `exists`: This was deprecated with the introduction of the missing value test operator. `exp1?exists` is equivalent with `exp1??`, also `(exp1)?exists` is equivalent with with `(exp1)??`.

  exists built-in

- `if_exists`: This was deprecated with the introduction of the default value operator. `exp1?if_exists` is similar to `exp1!`, and `(exp1)?if_exists` is similar to `(exp1)!`. The difference is that the default value with `if_exists` is not only empty string, empty sequence and empty hashs at the same time, but also boolean `false` and a transform that does nothing and ignores all parameters.

  if_exists built-in

- `web_safe`: the same as `html`

  web_safe built-in

#### Old-style macro and call directives

##### Synopsis

    <#macro name(argName1, argName2, ... argNameN)>
      ...
    </#macro>

    <#call name(argValue1, argValue2, ... argValueN)>

Where:

- `name`: name of the macro (not expression)

- `argName1`, `argName2`, ...etc.: the name of the local variables store the parameter values (not expression)

- `argValue1`, `argValue2`, ...etc.: expressions, the value of the parameters

##### Description

This is the documentation of FreeMarker 2.1 macro and macro related directives. These are still working, but deprecated. You may want to read the FreeMarker 2.2+ references: macro, return, user-defined directive call

A macro is a template fragment with an associated name. You can use that named fragment on multiple places in your template, so it helps in repetitive tasks. A macro can have parameters that influence the output generated when you use the macro.

You define a macro with the `macro` directive, and then you can use the defined macro in the whole template. The `macro` directive itself does not write anything to the output, it just defines the macro. For example this will define a macro called `warning`:

    <#macro warning(message)>
      <div align=center>
      <table border=1 bgcolor=yellow width="80%"><tr><td align=center>
        <b>Warning!</b>
        <p>${message}
      </td></tr></table>
      </div>
    </#macro>

The macro definition body (the section between the macro start-tag and end-tag) will be processed whenever you use the `call` directive with the name of the macro. For example this calls the macro called `warning`:

    <#call warning("Unplug the machine before opening the cover!")>

and will write this to the output:

      <div align=center>
      <table border=1 bgcolor=yellow width="80%"><tr><td align=center>
        <b>Warning!</b>
        <p>Unplug the machine before opening the cover!
      </td></tr></table>
      </div>

The parameters passed in as parameters to the `call` directive will be accessible in the macro definition body as local variables.

When you call a macro, you must specify the same number of parameters as were specified in the macro definition. For example if this is the macro definition:

    <#macro test(a, b, c)>Nothing...</#macro>

then these are valid macro calls:

    <#call test(1, 2, 3)>
    <#call test("one", 2 + x, [1234, 2341, 3412, 4123])>

If a macro has no parameters, then you can omit the parentheses:

    <#macro test>mooo</#macro>
    <#call test>

When you define a macro it will be available in the template, where you have defined it only. But probably you want to use the same macros in more templates. In this case you can store your macro definitions in a common file, and then include that file in all templates where you need those macros.

It's fine to call a macro that's defined further down in the template (since macros are defined at parse time, not in process time). However, if the macro definitions are inserted with `include` directive, they will not be available until FreeMarker has executed the `include` directive.

You can leave a macro definition body before the `</#macro>` tag with the `return` directive.

#### Transform directive

##### Synopsis

    <transform transVar>
      ...
    </transform>
    or
    <transform transVar name1=value1 name2=value2 ... nameN=valueN>
      ...
    </transform>

Where:

- `transVar`: Expression evaluates to a transform

- `name1`, `name2`, ... `nameN`: Name of parameters. Literal value, not expression.

- `value1`, `value2`, ... `valueN`: Expressions evaluate to the values of parameters

##### Description

This directive is still working, but deprecated. You may want to read about user-defined directive calls to see the replacement.

Captures the output generated inside its body (i.e. between its start-tag and end-tag), and let the given transform modify it before it is written to the final output.

Example:

    <p>A very simple HTML file:
    <pre>
    <transform html_escape>
    <html>
      <body>
        <p>Hello word!
      </body>
    </html>
    </transform>
    </pre>

the output will be:

    <p>A very simple HTML file:
    <pre>
    &lt;html&gt;
      &lt;body&gt;
        &lt;p&gt;Hello word!
      &lt;/body&gt;
    &lt;/html&gt;
    </pre>

Some transforms may take parameters. The name and meaning of parameters depends on the transform in question. For example here we give a parameter called ``var'':

    <#-- This transform stores the output in the variable x,
         rather than sending it to the output -->
    <transform capture_output var="x">
    some test
    </transform>

It is the task of the programmers to put the necessary transforms into the data-model. For the name and usage of accessible transforms ask the programmers. Initially there is a shared variable for most transforms in the `freemarker.template.utility` package. For more information see:

transform directive

#### Old FTL syntax

With the old FTL syntax the `#` was not required (prior 2.1 not even allowed) in the FTL tags. For example, you could write this:

    <html>
    <head>
      <title>Welcome!</title>
    </head>
    <body>
      <h1>Welcome ${user}!</h1>
      <p>We have there animals:
      <ul>
      <list animals as being>
        <li>${being.name} for ${being.price} Euros
      </list>
      </ul>
      <include "common_footer.html">
    </body>
    </html>

While the `#`-less syntax was more natural for HTML authors, it had too many drawbacks, so finally we have decided to deprecate it. With the newer syntax (a.k.a ``strict syntax''), the `#` is strictly required. That is, things like `<include "common_footer.html">` will go to the output as is, since they are not considered as FTL tags. Note that user-defined directives use `@` instead of `#`.

However, to give users time to prepare for this change, in FreeMarker 2.1 and 2.2 the usage of `#` is optional, unless the programmer enables strict syntax mode in the FreeMarker configuration by calling `setStrictSyntaxMode(true)` on `Configuration`. In fact, we strongly recommend this to programmers. Starting from some later release this setting will be initially set to `true`. Also, you can specify if you want to use strict syntax or old syntax in the template files with the `ftl` directive.

The advantages of ``strict syntax'' over the legacy FTL syntax are:

- Since all `<#...>` and `</#...>` are reserved for FTL:

  - We can introduce new directives without breaking backward compatibility.

  - We can detect if you made a typo, i.e. `<#inculde ...>` is treated as parse-time error, rather than silently treated as simple text.

  - It is easier for third-party tools to handle templates (e.g. do syntax highlighting), especially since they don't have to know about the new directives introduced with new releases.

  - Templates are more readable, since it is easier to spot `<#...>` tags embedded into HTML or other markup.

- `<#` and `</#` is illegal XML (except in CDATA sections), and illegal in almost all other SGML applications, so they can't interfere with the tags used in the static text parts (e.g. if you have `include` element in the generated XML).

strict syntax
old FTL syntax
new FTL syntax

#### #{...}: Numerical interpolation

Deprecated: Use the `number_format` setting and the `string` built-in instead. For formatting for computer audience (i.e., no localized formatting) use the `c` built-in (like `number?c`).

##### Synopsis

    #{expression}
    or
    #{expression; format}

Where:

- `expression`: expression that can be evaluated as a number.

- `format`: optional format specifier.

##### Description

The numerical interpolation is used to output a number value. If the expression doesn't evaluate to a number, the evaluation ends with an error.

The optional format specifier specifies the minimum and the maximum number of displayed fractional digits using syntax `mminMmax`. For example, `m2M5` means "at least two, at most five fractional digits". The minimum or the maximum specifier part can be omitted. If only the minimum is specified, the maximum is equal to the minimum. If only maximum is specified, the minimum is 0.

The decimal separator character of the output is internationalized (according the current locale setting), which means that it is not necessarily a dot.

Unlike `${...}`, `#{...}` ignores the `number_format` setting. This is actually a backward compatibility quirk, but it can be useful when you print numbers in situations like `<a href="quertyDatabase?id=#{id}">`, where you surely don't want grouping separators or something fancy like that. However, starting from FreeMarker 2.3.3 rather use the `?c` built-in for this purpose, like `<a href="quertyDatabase?id=${id?c}">`.

Examples. Assume that `x` is `2.582` and `y` is `4`:

               <#-- If the language is US English the output is: -->
    #{x}       <#-- 2.582 -->
    #{y}       <#-- 4 -->
    #{x; M2}   <#-- 2.58 -->
    #{y; M2}   <#-- 4    -->
    #{x; m1}   <#-- 2.6 -->
    #{y; m1}   <#-- 4.0 -->
    #{x; m1M2} <#-- 2.58 -->
    #{y; m1M2} <#-- 4.0  -->

#{...}
deprecated

## Appendixes

### FAQ

JSP versus FreeMarker?

JSP

Note: JSP 1.x was really bad as an MVC template engine because it was not made for that, so I don't deal with that here. We compare FreeMarker with the JSP 2.0 + JSTL combo.

FreeMarker Pros:

- FreeMarker is not tied to Servlets, networking or the Web; it is just a class library to generate text output by merging a template with Java objects (the data-model). You can execute templates anywhere and anytime; no HTTP request forwarding or similar tricks needed, no Servlet environment needed at all. Because of this you can easily integrate it into any system.

- No servlet specific scopes and other highly technical things in templates. It was made for MVC from the beginning, it focuses only on the presentation.

- You can load the templates from anywhere; from the class path, from a data-base, etc.

- Locale sensitive number and date formatting by default. Since we mostly output for a human audience all you need to do is just write `${x}` rather than `<fmt:formatNumber value="${x}" />`. You can easily switch this behavior and output non-localized numbers by default.

- Easier to define ad-hoc macros and functions.

- No sweeping errors under the carpet. Missing variables will cause an error by default, and not silently default to arbitrary values. Also, `null`-s are not treated silently as 0/false/empty string. See more about this here...

- ``Object wrapping''. This lets you show the objects to templates in a customized, presentation oriented way (e.g. see here how a W3C DOM nodes can be seen by templates using this technology.)

- Macros and functions are just variables (compare it to how JSP custom tags work), so they can be easily passed around as parameter values, put into the data-model, ...etc, just like any other value.

- Easier to read, more terse syntax. For example: `<#if x>...</#if>` instead of `<c:if test="${x}">...</c:if>`

- Virtually unnoticeable delay when visiting a page for the first time (or after it was changed), because no expensive compilation happens.

FreeMarker Cons:

- Not a ``standard''. There are fewer tools and IDE integrations, fewer developers knows it and there's much less industry support in general. (However, JSP tag libraries work without modification in FreeMarker templates, if they are not using `.tag` files.)

- Since macros and function are just variables, incorrect directive and parameter names and missing required parameters can be detected only on runtime.

- Its syntax doesn't follow the HTML/XML rules apart from some visual similarity, which is confusing for new users. (It's the price of the terseness...)

- Doesn't work with JSF. (It could work technically, but nobody has implemented that yet.)

You may read this if you are considering replacing JSP with FreeMarker:

Velocity versus FreeMarker?

Velocity

Velocity is a simpler, more lightweight tool. Thus, it does not address many tasks that FreeMarker does, and its template language is less powerful in general, but it is simpler; visit http://freemarker.org/fmVsVel.html for details. Currently (2005) Velocity has wider third party support and larger user community.

Why is FreeMarker so picky about `null`-s and missing variables, and what to do with it?

To recapitulate what's this entry is about: FreeMarker by default treats an attempt to access a non-existent variable or a `null` value (this two is the same for FreeMarker) as error, which aborts the template execution.

First of all, you should understand the reason of being picky. Most scripting languages and template languages are rather forgiving with missing variables (and with `null`-s), and they usually treat them as empty string and/or 0 and/or logical false. This behavior has several problems:

- It potentially hides accidental mistakes, like a typo in a variable name, or when the template author refers to a variable that the programmer doesn't put into the data-model, or for which the programmer uses a different name. Human is prone to do such accidental mistakes, computers are not, so missing this opportunity that the template engine can show these errors is a bad business. Even if you very carefully check the output of the templates during development, it is easy to look over mistakes like `<#if hasDetp>print dept here...</#if>`, which would then silently never print the dept of the visitor, since you have mistyped the variable name (it should be `hasDept`). Also think about maintenance, when you later modify your application... most probably you will not re-check templates that carefully each time.

- Makes dangerous assumptions. The script language or template engine knows nothing about the application domain, so when it decides the value of something it don't know to be 0/false, it is a quite irresponsible and arbitrary thing. Just because it is not know what's your current bank account balance, can we just say it is $0 (and how easy it is to accidentally write `Balance: ${balanace}`)? Just because it is not known if a patient has penicillin allergy, we can just say he/she doesn't have (and how easy it is to accidentally write `<#if hasPenicilinAllergy>Warning...<#else>Allow...</#if>`; there is a typo in this, if you didn't see)? Just consider the implications of such mistakes for a moment. They can be quite severe and troubling. Showing an error page is often better than showing incorrect information that formally looks good.

Being not picky is mostly sweeping under the carpet in this case (not facing with the problems), which of course most people feels more convenient, but still... we believe that in most cases being strict will save your time and increase your software quality in the long run.

On the other hand, we recognize that there are cases where you don't want FreeMarker to be that picky with good reason, and there is solution for them:

- It's often normal that your data-model contains `null`-s or have optional variables. In such cases use these operators. If you use them too often, try to rethink your data-model, because depending on them too much is not just results in awkward verbose templates, but increases the probability of hiding errors and printing arbitrary incorrect output (for the reasons described earlier).

- On a production server you may rather want to show an incomplete/damaged page than an error page. In this case you can use other error handler than the default. Error handlers can be made that rather skip the problematic part than abort the whole page rendering. Note, however, that although the error handlers don't give arbitrary default values to variables, for pages that show critical information it's maybe still better to show an error page. (Another feature you may interested in: the `attempt`/`recover` directives)

The documentation writes about feature X, but it seems that FreeMarker doesn't know that, or it behaves in a different way as documented, or a bug that was supposedly fixed is still present.

Are you sure that you are using the documentation written for the same version of FreeMarker that you actually use? Especially, note that our online documentation is for the latest usable FreeMarker release. You may use an older release.

Are you sure that the Java class loader finds the same `freemarker.jar` that you expect to use? Maybe there is an older version of `freemarker.jar` around (such as in the Ant `lib` directory), which has higher priority. To check this, try to print the version number in a template with `${.version}`. If it dies with ``Unknown built-in variable: version'' error message, then you use a release before 2.3-final or 2.2.8, but you can still try to get the version number in the Java code of your application with `Configuration.getVersionNumber()`. If this method is not present either, then you are using an early 2.3-preview, or a version before 2.2.6.

If you think that the documentation or FreeMarker is wrong, please report it using the bug tracker, or the mailing list, or the forums on http://sourceforge.net/projects/freemarker/. Thank you!

Why does FreeMarker print the numbers with strange formatting (as 1,000,000 or 1 000 000 instead of 1000000)?

FreeMarker uses the locale-sensitive number formatting capability of the Java platform. The default number format for your locale may uses grouping or other unwanted formatting. To prevent this, you have to override the number format suggested by the Java platform with the `number_format` FreeMarker setting. For example:

    cfg.setNumberFormat("0.######");  // now it will print 1000000
    // where cfg is a freemarker.template.Configuration object

Note however than humans often find it hard to read big numbers without grouping separator. So in general it is recommended to keep them, and in cases where the numbers are for ''computer audience'' that is confused on the grouping separators, use the `c` built-in. For example:

    <a href="/shop/productdetails?id=${product.id?c}">Details...</a>

Why does FreeMarker print bad decimal and/or grouping separator symbol (as 3.14 instead of 3,14)?

Different countries use different decimal/grouping separator symbols. If you see incorrect symbols, then probably your locale is not set properly. Set the default locale of the JVM or override the default locale with the `locale` FreeMarker setting. For example:

    cfg.setLocale(java.util.Locale.ITALY);
    // where cfg is a freemarker.template.Configuration object

However, sometimes you want to output a number not for human audience, but for ``computer audience'' (like you want to print a size in CSS), in which case you must use dot as decimal separator, regardless of the locale (language) of the page. For that use the `c` built-in, for example:

    font-size: ${fontSize?c}pt;

Why does FreeMarker give an error when I try to print a boolean like `${aBoolean}`, and how to fix it?

Unlike numbers, booleans has no commonly accepted format, not even a common format within the same page. Like when you show on a HTML page if a product is washable, you will hardly want to show for the visitor "Washable: true", but rather "Washable: yes". So we force the template author (by `${washable}` causing error) to find out with his human knowledge how the boolean value should be shown at the given place. The common way of formatting a boolean is like `${washable?string("yes", "no")}`, `${caching?string("Enabled", "Disabled")}`, `${heating?string("on", "off")}`, etc. However, for generating source code `${washable?string("true", "false")}` would be very often used, so `${washable?string}` (i.e., omitting the parameter list) is equivalent with that.

The `<` and `>` of FreeMarker tags confuses my editor or the XML parser. What to do?

Starting from FreeMarker 2.3.4 you can use `[` and `]` instead of `<` and `>`. For more details read this...

What are the legal variable names?

variables names

FreeMarker has no limitations regarding the characters used in variable names, nor regarding the length of the variable names, but for your convenience try to chose variable names that can be used with the simple variable reference expressions (see it here). If you have to choose a more extreme variable name, that's not a bid problem either: see here.

How can I use variable (macro) names that contain space, dash or other special characters?

If you have a variable with strange name, such as `foo-bar`, FreeMarker will misinterpret what do you want when you write thing as `${foo-bar}`. In this concrete case, it will believe that you want subtract the value of `bar` from `foo`. This FAQ entry explains how to handle situations like this.

First of all it should be clean that these are just syntactical problems. FreeMarker has no limitations regarding the characters used in variable names, nor regarding the length of the variable names, but sometimes you need to use syntactical tricks.

If you want to read the variable: Use the square bracket syntax. An example of square bracket syntax is `baaz["foo"]`, which is equivalent with `baaz.foo`. As the subvariable name with the square bracket syntax is a string literal (in fact, arbitrary expression), it let you write `baaz["foo-bar"]`. Now you may say that it can be used for hash subvariables only. Yes, but top-level variables are accessible through special hash variable `.vars`. For example, `foo` is equivalent with `.vars["foo"]`. So you can also write `.vars["foo-bar"]`. Naturally, this trick works with macro invocations too: `<@.vars["foo-bar"]/>`

If you want to create or modify the variable: All directives that let you create or modify a variable (such as `assign`, `local`, `global`, `macro`, `function`, etc.) allows the quotation of the destination variable name. For example, `<#assign foo = 1>` is the same as `<#assign "foo" = 1>`. So you can write things like `<#assign "foo-bar" = 1>` and `<#macro "foo-bar">`.

Why do I get "java.lang.IllegalArgumentException: argument type mismatch" when I try to use X JSP custom tag?

On JSP pages you quote all parameter (attribute) values, it does not mater if the type of the parameter is string or boolean or number. But since custom tags are accessible in FTL templates as plain user-defined FTL directives, you have to use the FTL syntax rules inside the custom tags, not the JSP rules. Thus, according to FTL rules, you must not quote boolean and numerical parameter values, or they are interpreted as string values, and this will cause a type mismatch error when FreeMarker tries to pass the value to the custom tag that expects non-string value.

For example, the `flush` parameter to Struts Tiles `insert` tag is boolean. In JSP the correct syntax was:

    <tiles:insert page="/layout.jsp" flush="true"/>
    ...

but in FTL you should write:

    <@tiles.insert page="/layout.ftl" flush=true/>
    ...

Also, for similar reasons, this is wrong:

    <tiles:insert page="/layout.jsp" flush="${needFlushing}"/>
    ...

and you should write:

    <tiles:insert page="/layout.jsp" flush=needFlushing/>
    ...

(Not `flush=${needFlushing}`!)

How to include other resources in a way as `jsp:include` does it?

Not with `<#include ...>`, as that just includes another FreeMarker template without involving the Servlet container.

Since the inclusion method you look for is Servlet-related, and pure FreeMarker is unaware of Servlets or even HTTP, it's the Web Application Framework that decides if you can do this and if so how. For example, in Struts 2 you can do this like this:

    <@s.include value="/WEB-INF/just-an-example.jspf" />

If the FreeMarker support of the Web Application Framework is based on `freemarker.ext.servlet.FreemarkerServlet`, then you can also do this (since FreeMarker 2.3.15):

    <@include_page path="/WEB-INF/just-an-example.jspf" />

but if the Web Application Framework provides its own solution, then you may prefer that, after all it may does something special.

For more information about `include_page` read this...

How can I get the parameters to my plain-Java-method/`TemplateMethodModelEx`/`TemplateTransformModel`/`TemplateDirectiveModel` implementation as plain `java.lang.*`/`java.util.*` objects?

Unfortunately, there is no simple general-purpose solution for this problem. The problem is that FreeMarker object wrapping is very flexible, which is good when you access variables from templates, but makes unwrapping on the Java side a tricky question. For example, it is possible to wrap a non-`java.util.Map` object as `TemplateHashModel` (FTL hash variable). But then, it can't be unwrapped to `java.util.Map`, since there is no wrapped `java.util.Map` around at all.

So what to do then? Basically there are two cases:

- Directives and methods that are written for presentation purposes (like kind of ``tools'' for helping FreeMarker templates) should declare their arguments as `TemplateModel`-s and the more specific sub interfaces of that. After all, the object wrapping is about apparently transforming the data-model to something that serves the purpose of the presentation layer, and these methods are part of the presentation layer.

- Methods that are not for presentation related tasks (but for business logic and like) should be implemented as plain Java methods, and should not use any FreeMarker specific classes at all, since according the MVC paradigm they must be independent of the presentation technology (FreeMarker). If such a method is called from a template, then it is the responsibility of the object wrapper to ensure the conversion of the arguments to the proper type. If you use the `DefaultObjectWrapper` or the `BeansWrapper` then this will happen automatically (but be sure you are using at least FreeMarker 2.3.3). Furthermore if you use `BeansWrapper`, then the method will surely get exactly the same instance that was earlier wrapped (as far as it was wrapped by the `BeansWrapper`).

Why I can't use non-string key in the `myMap[myKey]` expression? And what to do now?

hash key type

The ``hash'' type of the FreeMarker Template Language (FTL) is not the same as Java's `Map`. FTL's hash is an associative array too, but it uses string keys exclusively. This is because it was introduced for subvariables (as `password` in `user.password`, which is the same as `user["password"]`), and variable names are strings.

So FTL's hashes are not general purpose associate arrays that could be used for looking up values with keys of arbitrary type. FTL is presentation oriented language, and it has no feature dedicated for that purpose. It has, however, methods. Methods are part of the data-model, and they can do all kind of fancy data-model related calculations, so of course you can add some methods to the data-model for `Map` lookup. The bad news is that the building of the data-model, as it's an application specific issue, is the task of the programmers who use FreeMarker, so it's their task to ensure that such methods are present there to serve the template authors. (However, when template authors need to call methods that are not about presentation, then consider if the data-model is simple enough. Maybe you should push some calculations back to the data-model building phase. Ideally the data-model contains what should be displayed, and not something that serves as the base of further calculations.)

If you read the programmer's guide, then you know that technically, the data-model is a tree of `freemarker.template.TemplateModel` objects. The building of the data-model usually (but not necessary) happens by automatically wrapping (enclosing) plain Java objects into `TemplateModel` objects. The object that does this wrapping is the object wrapper, and it's specified when you configure FreeMarker. FreeMarker comes with a few object wrapper implementations out-of-the-box, and probably the most widely used of them is `freemarker.ext.beans.BeansWrapper`. If you use an instance of this as the object wrapper, then `java.util.Map`-s you put into the data-model will also act as a method, so you can write `myMap(myKey)` in the template, that will internally call `Map.get(myKey)`. There will be no restriction regarding the type of `myKey`, as `Map.get(Object key)` has no such restriction. If the value of `myKey` was wrapped with `BeansWrapper` or other object wrapper whose wrapped objects support unwrapping, or it is given as literal in the template, then the value will be automatically unwrapped to plain Java object before the actual invocation of the `Map.get(Object key)` method, so it will not be invoked with `TemplateModel`-s.

But there still will be a problem. Java's `Map` is particular about the exact class of the key, so for numerical keys calculated inside the templates you will have to cast them to the proper Java type, otherwise the item will not be found. For example if you use `Integer` keys in a Map, then you have to write `${myMap.get(123?int)}`. This is an ugly effect caused by that FTL's deliberately simplified type system just has a single numerical type, while Java distinguishes a lot of numerical types. (Ideally, in the above case, the programmers ensure that the `get` method automatically converts the key to `Integer`, so it's not the problem of the template author. This can be done with wrapper customization, but the wrapper has to know that the particular `Map` object uses `Integer` keys, which assumes application specific knowledge.) Note that the casting is not needed when the key value comes directly from the data-model (i.e. you didn't modified its value with arithmetical caluclations in the template), including the case when it's the return value of a method, and it was of the proper class before wrapping, because then the result of the unwrapping will be of the original type.

When I list the contents of a map (a hash) with `?keys`/`?values`, I get the `java.util.Map` methods mixed with the real map entries. Of course, I only want to get the map entries.

Certainly you are using `BeansWrapper` as your object wrapper, or a custom subclass of it, and the `simpleMapWrapper` property of that is left to `false`. Unfortunatelly, it's the default (for backward compatibility), so you have to explicitly set it to `true` where you create the object wrapper.

How can I modify sequences (lists) and hashes (maps) in FreeMarker templates?

modify hashes
modify sequences
sequence modify
hash modify

First of all, you may don't want to modify the sequence/hash, just concatenate (add) two or more of them, which results in a new sequence/hash, rather than modifying an existing one. In this case use the sequence concatenation and hash concatenation operators. Also, you may use the subsequence operator instead of removing sequence items. However, be aware of the performance implications: these operations are fast, but the hashes/sequences that are the result of many subseqent applications of these operations (i.e. when you use the result of the operation as the input of yet another operation, and so on) will be slow to read.

Now if you still want to modify sequences/hashes, then read on...

The FreeMarkes Template Language doesn't support the modification of sequences/hashes. It's for displaying already calculated things, not for calculating data. Keep templates simple. But don't give it up, you will see some advices and tricks bellow.

The best is if you can divide the work between the data-model builder program and the template so that the template doesn't need to modify sequences/hashes. Maybe if you rethink your data-model, you will realize this is possible. But, seldom there are cases where you need to modify sequences/hashes for some complex but purely presentation related algorithms. It seldom happens, so think twice whether that calculation (or parts of it) rather belongs to the data-model domain than to the presentation domain. Let's assume you are sure it belongs to the presentation domain. For example, you want to display a keyword index on some very smart way, whose algorithm need you to create and write some sequence variables. Then you should do something like this (ugly situations has ugly solutions...):

    <#assign caculatedResults =
        'com.example.foo.SmartKeywordIndexHelper'?new().calculate(keywords)>
    <#-- some simple algorithms comes here, like: -->
    <ul>
      <#list caculatedResults as kw>
        <li><a href="${kw.link}">${kw.word}</a>
      </#list>
    </ul>

That is, you move out the complex part of the presentation task from the template into Java code. Note that it doesn't affect the data-model, so the presentation is still kept separated from other the other application logic. Of course the drawback is that for this the template author will need the help of a Java programmer, but for complex algorithms that's probably needed anyway.

Now, if you still say you need to modify sequences/hashes directly with the FreeMarker template, here are two solutions, but please read the warning after them:

- You can write a `TemplateMethodModelEx` and `TemplateDirectiveModel` implementation that can modify certain types of sequences/hashes. Just certain types, because `TemplateSequenceModel` and `TemplateHashModel` doesn't have methods for modification, so you will need the sequence or hash to implement some additional methods. An example of this solution can be seen in FMPP. It allows you to do things like this (`pp` stores the services provided by FMPP for templates):

      <#assign a = pp.newWritableSequence()>
      <@pp.add seq=a value="red" />

  The `pp.add` directive works only with sequences that were created with `pp.newWritableSequence()`. So for example the template author can't modify a sequence that comes from the data-model with this.

- A sequence can have some methods/directives if you use a customized wrapper (so you can `<@myList.append foo />`). (Also, if you use `BeansWrapper` and configure it so it exposes the public methods, you can use the Java API for variables that are for `java.util.Map`-s and `java.util.List-s`. Just like with Apache Velocity.)

But beware, these solutions have a problem: The sequence concatenation, sequence slice operator (like `seq[5..10]`) and `?reverse` do not copy the original sequence, just wraps it (for efficiency), so the resulting sequence will change if the original sequence is changed later (an abnormal aliasing effect). The same problem exists with the result of hash concatenation; it just wraps the two hashes, so the resulting hash will magically change if you modify the hashes you have added earlier. As a work-around, after you did the above problematic operations, either be sure you will not modify the objects that were used as input, or create a copy of the result with a method provided by the solution described in above two points (e.g. in FMPP you could do `<#assign b = pp.newWritableSequence(a[5..10])>` and `<#assign c = pp.newWritableHash(hashA + hashB)>`). Of course this is easy to miss... so again, rather try to build the data-model so you will not need to modify collections, or use a presentation task helper class as was shown earlier.

What about `null` and the FreeMarker template language?

null

The FreeMarker template language doesn't know the Java language `null` at all. It doesn't have `null` keyword, and it can't test if something is `null` or not. When it technically faces with a `null`, it treats it exactly as a missing variable. For example, both if `x` is `null` in the data-model and if it's not present at all, `${x!'missing'}` will print ``missing'', you can't tell the difference. Also, if for example you want to test if a Java method has returned `null`, just write something like `<#if foo.bar()??>`.

You may interested in the rationale behind this. From the viewpoint of the presentation layer a `null` and non-existent thing is almost always the same. The difference between this two is usually just a technical detail, which is rather the result of implementation details than of the application logic. That you can't compare something to `null` (unlike in Java); it doesn't make sense to compare something with `null` in a template, since the template language doesn't do identity comparison (like the Java `==` operator when you compare two objects) but the more common sense value comparison (like Java's `Object.equals(Object)`; that doesn't work with `null` either). And how could FreeMarker tell if something concrete equals with something that is missing and thus unknown? Or if two missing (unknown) things are equal? Of course these questions can't be answered.

There is at least one problem with this `null`-unaware approach. When you call a Java method from a template, you may want to pass a `null` value as argument (since the method was designed to be used in Java language, where the concept of `null` is known). In this case you can exploit a bug of FreeMarker (that we will not fix until we provide a correct solution for passing `null` values to a method): if you specify a missing variable as the argument, then it will not cause an error, but a `null` will be passed to the method instead. Like `foo.bar(nullArg)` will call the `bar` method with `null` as argument, assuming that there is no varaible exists with ``nullArg'' name.

How can I use the output of a directive (macro) in expressions (as a parameter to another directive)?

Capture the output into a variable with the `assign` or `local` directive. For example:

    <#assign capturedOutput><@outputSomething /></#assign>
    <@otherDirective someParam=capturedOutput />

Why do I have ``?''-s in the output instead of character X?

This is because the character that you want to print can't be represented with the charset (encoding) used for the output stream, so the Java platform (not FreeMarker) substitutes the problematic character with question mark. In general you should use the same charset for the output as for the template (use the `getEncoding()` method of the template object), or which is even safer, you should always use UTF-8 charset for the output. The charset used for the output stream is not decided by FreeMarker, but by you, when you create the `Writer` that you pass to the `process` method of the template.

Example: Here I use UTF-8 charset in a servlet:

    ...
    resp.setContentType("text/html; charset=utf-8");
    Writer out = resp.getWriter();
    ...
    t.process(root, out);
    ...

Note that the question marks (or other substitution characters) may be produced outside FreeMarker, in which case the above obviously will not help. For example a bad/missconfigured database connection or JDBC driver may bring the text already with substitution characters in it. HTML forms are another potential source of encoding problems. It's a good idea to print the numerical code of the characters of the string on various places, to see where the problem occurs first.

You can read more about charsets and FreeMarker here...

How to retrieve values calculated in templates after template execution done?

First of all, be sure your application is designed well: templates should display data, and almost never calculate data. If you are still sure you want to do it, read on...

When you use `<#assign x = "foo">`, then you do not actually modify the data-model (since that is read-only, see: ), but create the `x` variable in the runtime environment of the processing (see ). The problem is that this runtime environment will be discarded when `Template.process` returns, as it was created for a single `Template.process` call:

    // internally an Environment will be created, and then discarded
    myTemplate.process(root, out);

To prevent this, you can do the below, which is equivalent with the above, except that you have chance to return the variables created in the template:

    Environment env = myTemplate.createProcessingEnvironment(root, out);
    env.process();  // process the template
    TemplateModel x = env.getVariable("x");  // get variable x

Can I allow users to upload templates and what are the security implications?

security user-provided templates

In general you shouldn't allow that, unless those users are system administrators or other trusted personnel. Consider templates as part of the source code just like `*.java` files are. If you still want to allow users to upload templates, here are what to consider:

- Denial-of-Service (DoS) attacks: It's trivial to create templates that run practically forever (with a loop), or exhaust memory (by concatenating to a string in a loop). FreeMarker can't enforce CPU or memory usage limits, so this is something that has no solution on the FreeMarker-level.

- Data-model and wrapping (`Configuration.setObjectWrapper`): By default the data-model gives access to the full public API of the Java objects that you have put into the it (with some exceptions). To avoid that, you have to construct the data-model so that it only exposes the things that are necessary for the template. For that, use `SimpleObjectWrapper` and create the data-model purely from `Map`-s, `List`-s, `Array`-s, `String`-s, `Number`-s, `Boolean`-s and `Date`-s. Or, you can implement your own extremely restrictive `ObjectWrapper`, which for example could expose your POJO-s safely.

- Template-loader (`Configuration.setTemplateLoader`): Templates may load other templates by name (by path), like `<#include "../secret.txt">`. To avoid loading sensitive data, you have to use a `TemplateLoader` that double-checks that the file to load is something that should be exposed. FreeMarker tries to prevent the loading of files outside the template root directory regardless of template loader, but depending on the underlying storage mechanism, exploits may exist that FreeMarker can't consider (like, just as an example, `~` jumps to the user directory). Note that `freemarker.cache.FileTemplateLoader` checks the canonical paths, so that's maybe a good candidate for this task, yet, adding a file extension check (file must be `*.ftl`) is maybe a good idea.

- The `new` built-in (`Configuration.setNewBuiltinClassResolver`, `Environment.setNewBuiltinClassResolver`): It's used in templates like `"com.example.SomeClass"?new()`, and is important for FTL libraries that are partially implemented in Java, but shouldn't be needed in normal templates. While `new` will not instantiate classes that are not `TemplateModel`-s, FreeMarker contains a `TemplateModel` class that can be used to create arbitrary Java objects. Other "dangerous" `TemplateModel`-s can exist in you class-path. Plus, even if a class doesn't implement `TemplateModel`, its static initialization will be run. To avoid these, you should use a `TemplateClassResolver` that restricts the accessible classes (possibly based on which template asks for them).

How to implement a function or macro in Java Language instead of in the template language?

It's not possible (yet), but something very similar is possible if you write a class that implements `freemarker.template.TemplateMethodModelEx` or `freemarker.template.TemplateDirectiveModel` respectively, and then where you were write `<#function my ...>...</#function>` or `<#macro my ...>...</#macro>` you write `<#assign my = "your.package.YourClass "?``new``()>` instead. Note that using the `assign` directive for this works because functions (and methods) and macros are just plain variables in FreeMarker. (For the same reason you could also put `TemplateMethodModelEx` or `TemplateDirectiveModel` instances into the data-model before calling the template, or into the shared variable map (see: `freemarker.template.Configuration.setSharedVariable(String, TemplateModel)`) when you initialize the application.)

Why is FreeMarker logging suppressed for my application?

It's because FreeMarker does not find any logging system. To fix this, you must make available one of the following logging systems for your application: SLF4J (recommended), Apache Commons Logging, Log4J (`org.apache.log4j`), Avalon (`org.apache.log`), or use J2SE 1.4 or later (that contains `java.util.logging`). That is, the class-loader used with your application must find one of the mentioned classes. Until 2.4, if you want to use SLF4J or Commons Logging you need to do some extra steps; see here...

In my Servlet based application, how do I show a nice error page instead of a stack trace when error occurs during template processing?

First of all, use `RETHROW_HANDLER` instead of the default `DEBUG_HANDLER` (for more information about template exception handlers read this...). Now FreeMarker will not print anything to the output when an error occurs, so the control is in your hands. After you have caught the exception of `Template.process(...)` basically you can follow two strategies:

- Call `httpResp.isCommitted()`, and if that returns `false`, then you call `httpResp.reset()` and print a ``nice error page'' for the visitor. If the return value was `true`, then try to finish the page be printing something that makes clear for the visitor that the page generation was abruptly interrupted because of an error on the Web server. You may have to print a lot of redundant HTML end-tags and set colors and font size to ensure that the error message will be actually readable in the browser window (check the source code of the `HTML_DEBUG_HANDLER` in `src\freemarker\template\TemplateException.java` to see an example).

- Use full page buffering. This means that the `Writer` doesn't send the output to the client progressively, but buffers the whole page in the memory. Since you provide the `Writer` instance for the `Template.process(...)` method, this is your responsibility, FreeMarker has nothing to do with it. For example, you may use a `StringWriter`, and if `Template.process(...)` returns by throwing an exception, then ignore the content accumulated by the `StringWriter`, and send an error page instead, otherwise you print the content of `StringWriter` to the output. With this method you surely don't have to deal with partially sent pages, but it can have negative performance implications depending on the characteristic of the pages (for example, the user will experience more response delay for a long page that is generated slowly, also the server will consume more RAM). Note that using a `StringWriter` is surely not the most efficient solution, as it often reallocates its buffer as the accumulated content grows.

I'm using a visual HTML editor that mangles template tags. Will you change the template language syntax to accommodate my editor?

We won't change the standard version, because a lot of templates depend on it.

Our view is that the editors that break template code are themselves broken. A good editor should ignore, not mangle, what it doesn't understand.

You maybe interested in that starting from FreeMarker 2.3.4 you can use `[` and `]` instead of `<` and `>`. For more details read this...

How fast is FreeMarker? Is it true that 2.x is slower than 1.x (FreeMarker classic)?

First of all, don't forget that FreeMarker is only the view rendering component in an MVC system. Furthermore MVC templates tend to be simple: many static text with a few interpolations and loops and conditional block. So it is not like PHP or Model 1 JSP; your application performance is not affected that much by the execution time of templates.

FreeMarker is certainly fast enough that it will only very rarely be a bottleneck in your application. Rather, other factors such as the speed of the data-base operations or network bandwidth will likely dominate. The impact of FreeMarker performance could be noticeable only for really busy sites (say, over 30 hits per second per server), where almost all database data is cached. If you are finding FreeMarker slow, do make sure that the cache of parsed templates works well (`Configuration.getTemplate` be default uses caching). Parsing a template file is a relatively costly step; in most long-running server-side applications, you will want to parse a template once and have it be used many times. (Note that FreeMarker 2.1.4 and earlier versions have bugs that sometimes can ruin caching.)

FreeMarker 2.1 is slower than 1.7.1. This surely depends on your templates, but it could be slower by a factor of 2 or 3. But again, it does not means that response time will be 2 or 3 times slower; most FreeMarker user simply should not be able to perceive the change in the final response time.

How can my Java classes ask a template for information about its structure (e.g. a list of all the variables)?

In FreeMarker 2.2, `Template` has an undocumented method for examining the parsed template: `getRootTreeNode`.

But listing all accessed variables is not possible, because variable names can be dynamically generated from data. However, there's a more important reason why FreeMarker doesn't support this. The design of FreeMarker is based on the idea of a separation between business objects and presentation objects. This separation takes two forms:

1. The templates know what data to expect, but they don't know how it's generated.

2. The business objects know what data to produce, but they don't know how it's going to be displayed. Therefore, they don't know anything about templates.

Since the business objects don't rely on the templates, if you need to use them with some other presentation system, you won't have to rewrite your application.

Will you ever provide backward compatibility?

FreeMarker 2.0 was a complete rewrite of FreeMarker 1.x, by a new author. The 1.x series continues as separated project: FreeMarker Classic. Since 2.x follows different philosophy than 1.x, 2.0x releases were immature despite the high major version number. This caused further radical changes between 2.01 and 2.1. As of 2.1 things were much more matured, and 2.2 is almost backward compatible with 2.1. We hope that this tendency continues.

Currently, the rule is that releases with different second version number (as 2.1.x and 2.2.x) are not (fully) compatible. Releases where only the third version number differs (as 2.2.1 and 2.2.6) are compatible.

We always provide backward compatible bugfix releases for the released versions. So basically, you don't have to switch to a new, non-backward compatible release in an already written product. It's a something for something situation... FreeMarker recovers faster from design mistakes than many other projects, but the price of this is that major releases are not backward compatible. This is admittedly not optimal, it would be better if there are fewer design mistakes... but, well, it is the reality.

If we distribute FreeMarker with our product, do we have to release the source code for our product?

No. As of 2.0, FreeMarker is released under a BSD-style license. This means that source or binary distributions may be made freely, and can be included in other products, whether commercial or open source.

The only restrictions apply to the copyright of FreeMarker itself, and the use of FreeMarker or its contributors as endorsements of your own product. See the LICENSE for further details.

If you use FreeMarker, we hope you'll send us a link to some information about your product, but that's optional as well.

FAQ

### Installing FreeMarker

No real installation needed. Simply copy `lib/freemarker.jar` to a location where your Java application's class-loader will find it. For example, if you use FreeMarker in a web application, you probably want to put `freemarker.jar` into the `WEB-INF/lib` directory of your web application.

No real installation needed. Simply copy `lib/freemarker.jar` to a location where your Java application's ClassLoader will find it. For example, if you use FreeMarker in a web application, you probably want to put `freemarker.jar` into the `WEB-INF/lib` directory of your web application. (If you want to use FreeMarker with JSP Model-2 style (which also means that you can use custom JSP taglibs in the templates), some extra steps needed. For more information please see the chapter about servlets.)

However, some third party libraries have also be available for the class-loader, if you want to enable certain optional FreeMarker features:

- At least J2SE 1.4 is required for regular expression built-ins.

- At least J2SE 1.4 or a JAXP + DOM implementation + SAX implementation is needed for the XML wrapping.

- Jaxen (recommended, download here) or Apache Xalan is needed for XML XPath support. Please use at least Jaxen 1.1-beta-8, not older versions! Apache Xalan classes are included in Sun J2SE 1.4, 1.5 and 1.6 (and maybe later too), so no separate Xalan jar is needed with those versions.

- Obviously, `javax.servlet` classes are needed for `FreemarkerServlet`. Servlet version 2.2 or later is needed.

- For the custom JSP taglib support, you will need JSP 1.2 API classes. No JSP implementation needed, just the API. For more information please see the chapter about servlets.

- Obviously, Jython classes are needed for the Jython wrapper.

- JDOM is needed for the deprecated freemarker.ext.jdom package.

install

### Building FreeMarker

If you want to modify the source code and rebuild `freemarker.jar`, you need Ant 1.6.1 (or newer) and JDK 5 (or newer). If these are satisfied, just run Ant from the root directory of the distribution, and it will create the new `freemarker.jar`. Note that for the very first build you must be on-line, because the build task will download a lot of required dependencies (about 20 MB) into the `lib` subdirectory of distribution root directory.

Maybe you should check the new jar file against our test suite. This is done by running Ant with `test` target (go to the root directory of the distribution, and issue "ant test"). If the test fails, read the resulting `.txt` file in the `build/testcase` directory for more details.

Note that building a full distribution, which includes the FreeMarker Manual and the off-line Web site, is not possible purely from the source code that is included with the distribution. You will have to check out the "docgen" and "site" sub-projects from the SVN repository of FreeMarker for that.

build

### Versions

#### 2.3.19

Date of release: 2012-02-29

Don't miss the security related changes, they may affect your application!

##### Changes on the FTL side

- Attention: The output of ISO 8601 date/time formatting built-ins, introduced in 2.3.17, was slightly changed. From now on, the time zone offset, when it's displayed and it isn't `Z`, always includes the minutes. For example, `15:30:15+02` becomes to `15:30:15+02:00` in the template output. Both formats are valid according to ISO 8601 (so anything that expects ISO 8601 date/times should continue working), but only the last format complies with the XML Schema date/time formats, hence this change.

- New built-in for escaping inside JSON string literals: `json_string`.

- Bugfix: Wrong `#` tags were printed as static text instead of causing parsing error if there was no correct `#` tag earlier in the same template. Since fixing this would not be 100% backward compatible, the old behavior has remained, unless you set the `incompatible_enhancements` setting (`Configuration.setIncompatibleEnhancements(String)`) to `"2.3.19"` or higher.

##### Changes on the Java side

- Attention: This release contains two important security workarounds that unavoidably make it obvious how some applications can be exploited. FreeMarker can't solve these issues on all configurations, so please read the details instead of just updating FreeMarker! Also, these changes are not 100% backward compatible in theory, however it's not probable that they will break anything. The two changes are:

  - The character with character code 0 (`\u0000`) is not allowed in template paths anymore. When a path contains it, FreeMarker behaves as if the template was not found.

    This is to fix the security problem where a template path like `"secret.txt\u0000.ftl"` is used to bypass extension filtering in an application. FreeMarker itself doesn't care about the extension, but some applications decide based on the extension if they will delegate a path to FreeMarker. When they do with such a path, the C/C++ implementation behind the storage mechanism may sees the path as `"secret.txt"` as the 0 terminates the string in C/C++, and thus load a non-FTL file as a template, returning the file contents to the attacker.

    Note that some HTTP servers, notably Tomcat and Apache will block URL-s containing 0, but some others, like Jetty, doesn't.

  - `ClassTemplateLoader`, when it's created with base path `"/"` (like with `new ClassTemplateLoader(someClass, "/")`), will not allow template paths that contain colon earlier than any `/`, and will act like if the template was not found in such case.

    This is to fix the security problem where a template path like `"file:/etc/secret"` or `"http://example.com/malware.ftl"` is interpreted as a full URL by a `java.net.URLClassLoader` in the class-loader hierarchy. This is a quirk (or bug) of `java.net.URLClassLoader`.

    Beware, some frameworks use their own `TemplateLoader` implementations, and if those are vulnerable, they will remain so after updating FreeMarker too! Note that this exploit only works if the class-loader hierarchy contains an `URLClassLoader` and the class-loader is used to load templates without adding any prefix before the template path (other than `"/"`).

  These security issues mostly affect applications where the user (the visitor) can supply arbitrary template paths. This is not the case with properly built MVC applications, as there only the Controller can be addressed directly, and it's the Controller who specifies the template paths. But MVC applications based on JSP Model-2 often expose the MVC Views as URL-s ending with `.ftl`, thus allowing the user to give arbitrary paths to FreeMarker. Such applications should be secured with a `security-constratint` in `web.xml` as shown in the related Manual section. This should be done regardless of the current security fixes.

- `Configuration` has new methods: `removeTemplateFromCache(...)`. This will remove the given template for the given locale from the cache, so it will be re-loaded regardless of the template update delay when it's next time requested.

- `BeansWrapper` ignores setter methods from now when introspecting classes. They weren't used anyway, so they unnecessarily caused "`java.beans.IntrospectionException`: type mismatch between read and write methods" errors.

- `TemplateClassResolver.SAFER_RESOLVER` now disallows creating `freemarker.template.utility.JythonRuntime` and `freemarker.template.utility.Execute`. This change affects the behavior of the `new` built-in if FreeMarker was configured to use `SAFER_RESOLVER`, which is not the default until 2.4 and is hence improbable.

- Bug fixed: Calling varargs methods now indeed works. (Earlier it only worked for overloaded methods.)

- Bug fixed [1837697] [2831150] [3039096] [3165425]: Jython support now works with Jython 2.2 and 2.5.

- Bug fixed [3325103]: `TemplateException`-s and `ParseException`-s are now serializable.

#### 2.3.18

Date of release: 2011-05-21

##### Changes on the Java side

- Bugfix [3304568]: 2.3.17 didn't find TLD-s in `WEB-INF\lib\*.jar` unless they were explicitly pointed in the `web.xml` with a `taglib` element. This bug was introduced in 2.3.17.

##### Other changes

- Added `LICENSE.txt` and `NOTICE.txt` to `freemarker.jar` under `META-INF`.

#### 2.3.17

Date of release: 2011-05-17

It's possibly urgent to update to this version because of a security fix!

##### Changes on the FTL side

- `?seq_index_of` and `?seq_last_index_of` now works on collections (`freemarker.template.TemplateCollectionModel`-s) too, not only on sequences (`freemarker.template.TemplateSequenceModel`-s).

- `?long` now works for date, date-time or time values, and returns the milliseconds since the epoch (as `java.util.Date.getTime()`).

- To convert numbers (usually Java `long`-s) to date or date-time and time values, `?number_to_date`, `?number_to_time`, `?number_to_datetime` was added. See more here... (Unfortunately, `?date` and like can't be extended to support this due to backward compatibility issues.)

- New built-ins to format numbers with ISO 8601 "extended" format regardless of the current date/time formatting settings, and even regardless of the current time zone setting. For example `${myTimeStamp?iso_utc}` will print something like `2010-05-16T23:05:45Z`. See more here...

- New special variable, `now`. This returns the current date-time. Usage examples: "`Page generated: ${.now}`", "`Today is ${.now?date}`", "`The current time is ${.now?time}`".

- `?sort` and `?sort_by` now supports sorting boolean values.

- When using unsupported or unknown string built-in flags, FreeMarker will now log warnings (maximum 25 times per class-loader, to prevent flooding the log). It's certain that starting from FreeMarker 2.4 these will count as errors.

- Bug fixed [3047201]: Using regular expressions (like with `?match`) could cause lockup in multi-threaded environment, also memory leakage when using dynamically generated regular expressions.

- Bug fixed: `?seq_contains`, `?seq_index_of` and `?seq_last_index_of` has failed with non-`java.util.List` `java.util.Collection`-s that are wrapped with pure `BeansWrapper` (not the `DefaultObjectWrapper`) as `TemplateSequenceModel`. (See also: `getSupportsIndexedAccess()` below)

##### Changes on the Java side

- Security fix: Using carefully crafted template names (template paths) that contain code point 0 (`'\u0000'`), it was possible to load files from outside the template root directory like if they were FreeMarker templates. The root of the problem is that the underlying native C/C++ part (which belongs to the Java platform or to the OS) interprets the 0 as the end of the string, while Java (and hence FreeMarker and the Servlet container) doesn't. Thus a path that looked safe for FreeMarker become unsafe on the lower level. The problem is present with all ways of loading templates by name (`Configuration.getTemplate(...)`, `<#include ...>`, `<#import ...>`).

  You are not effected if you don't allow users to upload templates and also at least one of these stands:

  - In your system users can't provide arbitrary strings as template names (template paths). For example, if users are only allowed to visit the URL-s that belong to the MVC Controller (like they can't visit `*.ftl`) then they can't suggest arbitrary template names.

  - The template names are part of the path in the Web page URL, and your webserver or Servlet container disallows URL-s that contain `%00`, or terminate the URL at it before passing it to the servlets.

  - You are using `FileTemplateLoader` and linking is not allowed in it (by default it isn't allowed).

- FreeMarker now can log its messages directly using SLF4J or Apache Commons Logging. However, it will not use these logger libraries automatically, until 2.4; see more here... But it's recommended to switch to SLF4J now.

- New setting: `"auto_flush"`, `Configurable.setAutoFlush(boolean)`. Sets whether the output `Writer` is automatically flushed at the end of `Template.process(Object, Writer)` (and its overloads). The default is `true`, which corresponds to the earlier behavior. Using `false` is needed for example when a Web page is composed from several boxes (like portlets, GUI panels, etc.) that aren't inserted with `#include` (or with similar directives) into a master FreeMarker template, rather they are all processed with a separate `Template.process(...)` call. In a such scenario the automatic flushes would commit the HTTP response after each box, hence interfering with full-page buffering, and also possibly decreasing performance with too frequent and too early response buffer flushes.

- Added new setting: `Configuration.setNewBuiltinClassResolver(TemplateClassResolver)`, or `new_builtin_class_resolver` property. This allows you to specify how the `new` built-in (like in `"com.example.SomeClass"?new()`) resolves classes and which classes are accessible at all. If you are allowing not-so-much-trusted users to upload templates, you should be definitely interested; see the Java API docs of `freemarker.core.Configurable.setSetting` and `freemareker.template.Configuration.setNewBuiltinClassResolver`. Otherwise it's still recommended to set this to `TemplateClassResolver.SAFER_RESOLVER` (or `safer` if you are using properties), although that's not 100% backward compatible (see Java API docs) .

- Added `freemarker.cache.NullCacheStorage`: Setting this as the cache storage in `Configuration` disables caching.

- Added `getSupportsIndexedAccess()` to `freemarker.ext.beans.CollectionModel`, so one can check if `TemplateSequenceModel.get(int)` will work with a particular `CollectionModel` instance or not.

- Bug fixed [2992265]: JSP `FreeMarkerPageContext.include` behaved incorrectly.

- Bug fixed: When using FreeMarker's JSP support with JSP tags that use `javax.servlet.jsp.PageContext.pushBody` (like some Stripes tags), `"ArrayIndexOutOfBoundsException: -1"` occurred inside `freemarker.ext.jsp.FreeMarkerPageContext.popWriter`.

- Bug fixed [3033015]: `AllHttpScopesHashModel` used `WrappingTemplateModel.getDefaultObjectWrapper()` for wrapping variables in the page scope, while used the user-specified `ObjectWrapper` for all other scopes (request, session, etc.). Now it uses the user-specified wrapper in the page scope as well.

- Bug fixed [3128073]: `HashAdapther.containsKey(...)` returned `true` for a key that doesn't exist when unwrapping the key has failed. As a side effect of the fix, `BeansWrapper.CAN_NOT_UNWRAP` is now private; earlier it was public by mistake.

- Big fixed [3151085]: `freemarker.jsp.TaglibFactory` didn't locate tld files properly. This fix gives better compliance with JSP specification for resolving and loading tld files.

- Bug fixed: Unwrapping `null` with a `BeansWrapper` that had a custom null-model didn't result in `null`. Now both unwrapping `null` and the custom null-model gives `null`.

- Log messages doesn't contain line-breaks (CR or LF) anymore and quote paths and other arbitrary text with Java string literal syntax that also escapes `<` characters as `\u003C`. These address security concerns related to poor quality log appenders and buggy log readers. This change is mostly noticeable on template processing error entries, which will now quote the exception message. Note that how stack traces (the `Throwable` objects) are logged is still up to the logging framework you are using.

##### Other changes

- The DTD-s and XSD-s that are included in `freemarker.jar` under `freemarker/ext/jsp` are now under Apache Software License, Version 2. This is also clarified in the `LICENSE.txt`. Earlier these files had no clear license terms.

#### 2.3.16

Date of release: 2009-12-07

##### Changes on the Java side

- Fixed a bug that caused incorrect unwrapping of sequences to Java arrays (See bug report)

- Fixed a bug that caused rounding of float and double values (See bug report)

- Created a new `freemarker.runtime.attempt` category and exceptions caught in `<#attempt>` blocks are logged into it at a DEBUG severity.

- Fixing the (ages old) problem of `RhinoWrapper` not working with all versions of Rhino because of binary incompatible change of Rhino's `Undefined.instance`.

- Fixed bug where `TextUtil.XMLEncNQG` didn't escape `]]>` as `]]&gt;`.

- Fixed bug where the root directory couldn't be used as the template base directory, as `FileTemplateLoader` believed that the template is outside the base directory.

- Macro names can no longer be changed through the API.

- FreemarkerServlet now cooperates with Session Fixation Attack Protection in Spring Security, see forum discussion for details.

- Substantially improved performance of the `<#return>` directive.

##### Changes on the FTL side

- Fixed bug where `anXMLNode.@@markup` and `@@nested_markup` didn't escape `]]>` as `]]&gt;`.

#### 2.3.15

Date of release: 2008-12-16

##### Changes on the FTL side

- Bug fixed: Hash concatenation (like `hash1 + hash2`) shuffled the order of keys/values even if both hashes were ordered.

- In web pages that are based on the `FreemarkerServlet`, you can now use `<@include_page path="..."/>` to use servlet includes. See more here...

##### Changes on the Java side

- The `BeansWrapper` can automatically detect that classes were reloaded by JavaRebel.

- Fixed a bug that caused `null` to be returned from `Environment.getCurrentEnvironment()` while processing autoincludes and autoimports. (See bug report)

- Fixed a bug that caused `getObject(Object)` method on POJOs to not be recognized as a general get method.

- Substantially improved performance of the `<#break>` directive.

- `DeepUnwrap` now unwraps custom null model of the current object wrapper into a Java `null`.

#### 2.3.14

Date of release: 2008-09-01

##### Changes on the FTL side

- New built-in: `xhtml`. See more here...

- New special variable: `template_name`. See more here...

- Now you can use the values of parameters as the defaults of other parameters, for example `<#macro section title label=title>`. In earlier versions it worked unreliably. There are no restriction regarding the order of parameters, like `<#macro section label=title title>` works too.

- Added a new number format specifier, `computer`. This uses the same formatting as `exp?c`.

##### Changes on the Java side

- The constructor to `freemarker.ext.servlet.AllHttpScopesHashModel` is now public, allowing it to be reused in 3rd party web frameworks.

- Bugfix: `freemarker.ext.beans.SimpleMapModel` (unlike either `freemarker.ext.beans.MapModel` or `freemarker.template.SimpleHash`) didn't allow lookup by `java.lang.Character` key when passed a single-character string as a key.

- Bugfix: permissive unwrapping in `freemarker.template.utility.DeepUnwrap` class was not recursively permissive with elements of sequences and hashes.

- Bugfix: `freemarker.ext.beans.MapModel` returns `BeansWrapper.wrap(null)` instead of `null` for `null` values explicitly bound into the map.

- Bugfix: Fixed a subtle bug with property getters of classes implementing a type-parametrized interface.

- Bug fixed: A further corner case of [1939742].

#### 2.3.13

Date of release: 2008-05-05

##### Changes on the FTL side

- New built-ins for rounding numbers: `round`, `floor`, `ceiling`. See more here...

##### Changes on the Java side

- [1898300], [1818742], [1780882]: Reworked template caching mechanism for radically improved concurrent performance, with help from Azul Systems engineers. (Achieved 20x speedup with Struts2 webapps on a 128-CPU Azul device compared to 2.3.12.) Also, template loading (including parsing) errors are now cached, improving performance in applications that often try to get missing templates.

- [1892546] Allow for custom `TemplateLoader` in `FreemarkerServlet`.

- Bug fixed: [1725107] Using the FreeMarker JSP taglib support with Servlet 2.4 may generates XML validation warnings.

- Bug fixed: [1939742] `ConcurrentModificationException` on accessing nonexistent `SimpleHash` entries in a loop

- Bug fixed: [1902012] `IteratorModel` eats exception causes

- Bug fixed: `<#assign x></#assign>` (empty nested content) has caused `NullPointerException`

- Bug fixed: [1926150] `CachedTemplate` should be serializable

#### 2.3.12

Date of release: 2008-02-03

##### Changes on the Java side

- Bug fixed: [1857161] JSP `SimpleTag` support was broken in 2.3.11.

- In the templates, now you can conveniently call Java methods that use the Java 5 varargs feature (variable-length argument lists). Also the overloaded-method chooser logic now considers vararg methods more intelligently.

- Enum constants are now identified by their `name()` instead of by their `toString()` (because the latter can be overridden in subclasses). This doesn't affect the way enum constants are printed; of course that still uses `toString()`.

- Messages in parser exceptions now display the name of the template.

#### 2.3.11

Date of release: 2007-12-04

This release contains several performance and usability improvements.

##### Changes on the FTL side

- Bug fixed: [1687248] Warning! This bugfix may breaks some templates! Fixed the bugs of the `c` built-in (`?c`) that sometimes caused whole numbers to be formatted with ``.0'' at the end (like: 1.0), and caused numbers sometimes formatted to exponential form (like 4E-20). From now whole numbers will never use decimal dot (not even if the wrapped number is a `double`; remember, the template language knows only a single numerical type), and exponential form will never be used either. Also, the maximum number of digits after the decimal dot was limited to 16, so numbers smaller than 1E-16 will be shown as 0.

##### Changes on the Java side

- FreeMarker now has much better JSP 2.0 and JSP 2.1 compliance. Most notably, the JSP 2.0 `SimpleTag` interface is now supported. Additionally, even when run in an environment that doesn't have its own JSP implementation, the FreeMarker JSP runtime will make available its own implementation of `JspFactory` and `JspEngineInfo` to tags when JSP 2.0 API JAR is available in classpath, as well as an implementation of `JspApplicationContext` when JSP 2.1 API JAR is available in classpath.

- A new model interface, `TemplateDirectiveModel` provides an easier paradigm for implementing user-defined directives than `TemplateTransformModel` did previously. `TemplateTransformModel` will be deprecated.

- FreeMarker now finds the Xalan-based XPath support included in Sun JRE/JDK 5 and 6, so no separate Xalan jar is required for the XPath support to work. (However, we recommend Jaxen over Xalan, as the FreeMarker XPath support is more complete with that. Of course for that the Jaxen jar is still needed.)

- Wrapping performance of `BeansWrapper` has been significantly improved by eliminating repetitive execution of various class tests.

  Note for `BeansWrapper` customizers: subclasses of `BeansWrapper` that previously overrode `getInstance(Object, ModelFactory)` method should now instead override `getModelFactory(Class)` to take advantage of this improvement. Overriding the old method still works, but it will not take advantage of the performance improvement.

- Memory footprint of a wrapper created by `BeansWrapper` has been reduced (by a size of one default-sized `HashMap`) until methods or indexed properties are accessed on it (simple properties can be accessed without increasing memory footprint).

- Rhino objects can be used in templates as scalars, numbers, and booleans, following the JavaScript conversion semantics for these types.

- `.data_model` is now a `TemplatHashModelEx` when possible. This means that the list of the data-model variable names usually can be get with `.data_model?keys`.

- `FileTemplateLoader` can now optionally allow following symlinks that point out of the base directory. It is disabled by default for backward compatibility.

- Bug fixed: [1670887] `TaglibFactory` taglib matching did not follow JSP 1.2 FCS.

- Bug fixed: [1754320] Bug in `setXPathSupportClass` prevented plugging in a user-supplied `XPathSupport` implementation.

- Bug fixed: [1803298] Parser error while parsing macro with loop variables

- Bug fixed: [1824122] Loading templates from JAR files could lead to leaking of file handles (due to a bug in the Java API implementation of Sun).

- Bug fixed: Cached template is now removed from the cache if the re-loading of the modified template file fails, so no staled template is served.

##### Documentation changes

- Substantial reworkings in the Template Authors's Guide (which was previously called Designer's Guide), especially in the Getting Started section.

- `#{...}` is documented as deprected construct from now.

- The "transform" term is now removed from the documentation. Instead the more general "user-defined directive" term is used, which encompasses macros, `TemplateTransformModel`-s and the new `TemplateDirectiveModel`-s, which are just different ways of implementing user-defined directives.

- Some more minor improvements in the Manual.

#### 2.3.10

Date of release: 2007-04-20

This release contains several important bugfixes.

##### Changes on the Java side

- [1589245] `MultiTemplateLoader` clears its internal cached data (used for optimizing subsequent lookups of the same template) when `Configuration.clearTemplateCache()` is invoked.

- [1619257] A bug that caused an exception when `strict_bean_model` was used in a FreeMarker configuration `Properties` object or in the `<#setting .../>` directive has been fixed.

- [1685176] A bug that caused `StackOverflowError` in certain interactions of garbage collector with MRU cache under Sun's Java 6 JVM has been fixed.

- [1686955] When `ResourceBundleModel` constructs `MessageFormat` objects, it passes them its own locale. More info...

- [1691432] A bug that caused `BeansWrapper.EXPOSE_SAFE` to be no safer than `BeansWrapper.EXPOSE_ALL` has been fixed.

##### Changes on the FTL side

- [1628550] You can now use `dateExp?string.full` for formatting dates using Java built-in format `java.util.Date.FULL` More info...

#### 2.3.9

Date of release: 2007-01-23

This release contains support for accessing JDK 1.5 enums and public fields of classes from the templates through the BeansWrapper.

##### Changes on the Java side

- `BeansWrapper` can now expose public fields of objects to the template if you call the `setExposeFields(true)` on it. More info...

- `BeansWrapper` can now pass any sequence model to Java methods expecting a `java.util.Collection` or a native Java array (including primitive arrays). More info...

- `BeansWrapper` can now pass any sequence and collection model to Java methods expecting a `java.lang.Iterable`. More info...

- `BeansWrapper` can now unwrap numeric models into correct target types when passing to Java methods expecting a primitive or boxed number. Use of various expert built-ins to manually coerce the types becomes mostly unnecessary.

- Fixed a bug where `BeansWrapper` would pass a `java.util.Collection` to a method expecting a `java.util.Set` in certain rare cases. More info...

- Support for JDK 1.5 enums in `BeansWrapper` and `DefaultObjectWrapper`. By calling the `getEnumModels()` method, you can retrieve a hash model that is keyed by class names and allows access to enumerated values. I.e. if you bind this hash model under name `enums` in the data-model, you can write expressions like `enums["java.math.RoundingMode"].UP` in the template. The enum values can be used as scalars and support equality and inequality comparisons. More info...

- `freemarker.ext.rhino.RhinoWrapper` now correctly translates Rhino `Undefined` instance, `UniqueTag.NOT_FOUND`, and `UniqueTag.NULL` to FreeMarker undefined value.

#### 2.3.8

Date of release: 2006-07-09

This release substantially improves the JSP 2.0 compatibility. (For those who have seen the same points in 2.3.7: Sorry, the version history was incorrect... those JSP 2.0 related changes were not in the release yet.)

##### Changes on the Java side

- JSP support improvement: [1326058] Added support for `DynamicAttributes` (new in JSP 2.0)

- JSP support improvement: Added support for `pushBody()`/`popBody()` in `FreemarkerPageContext`

- JSP support improvement: Added support for `getVariableResolver()` (new in JSP 2.0).

- JSP support improvement: Added support for `include(String, boolean)` (new in JSP 2.0).

- JSP support improvement: Added support for `getExpressionEvaluator()` (new in JSP 2.0). However, it will need Apache commons-el in the class path, or else this method will not work (it's optional). Note that EL support is not needed in principle, since FreeMarker has it's own expression language. But some custom JSP 2 tags may still want to use this method, after all it's in the JSP 2 API.

#### 2.3.7

Date of release: 2006-06-23

This release, compared to 2.3.7 RC1, contains new operators for handling null/missing variables, , the `substring` built-in, and some more bugfixes. Note that 2.3.7 RC1 has a long change log, so you may want to read that too.

##### Changes on the Java side

- The `seq_contains` built-in now handles `TemplateCollectionModel`-s as well.

- Bug fixed: In 2.3.7 RC1 `FreemarkerServlet` has always died with `NullPointerException` during initialization.

##### Changes on the FTL side

- 3 new operators were added for terser missing variable handling. These operators make the `default`, `exists` and `if_exists` built-ins deprecated. (The parser doesn't issue any warning messages when you use deprecated built-ins, and they are still working.):

  - `exp1!exp2` is near equivalent with `exp1?default(exp2)`, also `(exp1)!exp2` is near equivalent with `(exp1)?default(exp2)`. The only difference is that this new operator doesn't evaluate the `exp2` when the default value is not needed.

  - `exp1!` is similar to `exp1?if_exists`, also `(exp1)!` is similar to `(exp1)?if_exists`. The difference is that with this new operator the default value is an empty string and an empty list and empty hash at the same time (multi-type variable), while with `if_exists` the default value was an empty string and an empty list and empty hash and boolean `false` and a transform that does nothing and ignores all parameters at the same time.

  - `exp1??` is equivalent with `exp1?exists`, also `(exp1)??` is equivalent with with `(exp1)?exists`.

- New built-in: `exp?substring(from, toExclusive)`, also callable as `exp?substring(from)`. Getting substrings was possible for a long time like `myString[from..toInclusive]` and `myString[from..]`. This syntax is now deprecated for getting substrings (but it's still working), and instead you should use `myString?substring(from, toExclusive)` and `myString?substring(from)`. Sequence (list) slices still has to be get with the old syntax, since `substring` only applies to strings. Please note that the ``to'' parameter is 1 greater with this new builtin, as it is an exclusive index. Further difference is that the `substring` built-in requires that the ``from'' index is less than or equal to the ``to'' index. So 0 length substrings are possible now, but not reversed substrings.

- Bug fixed: [1487694] malfunction when the `recover` directive has no nested content

#### 2.3.7 RC1

Date of release: 2006-04-27

This release contains many bugfixes and some `FreemarkerServlet` related improvements. It's a Release Candidate, which means that it shouldn't be used in production environment yet. We recommend this release for development, however. Please test it.

##### Changes on the Java side

- `FreemarkerServlet` improvement: `AllHttpScopesHashModel` is now public, so you can add unlisted variables to the data-model.

- `FreemarkerServlet` improvement: When it throws a `ServletException`, the J2SE 1.4 cause exception is now set under J2SE 1.4.

- Bug fixed: [1469275] `NullPointerException` when using `BeansWrapper` with reloaded classes

- Bug fixed: [1449467] `HttpSessionHashModel` is not `Serializable`

- Bug fixed: [1435113] Error in `BeanWrapper` with indexed properties

- Bug fixed: [1411705] Acquisition bug in `TemplateCache`

- Bug fixed: [1459699] Tag syntax can't set with `Configuration.setSetting(String, String)`

- Bug fixed: [1473403] `ReturnInstruction.Return` should be public

##### Changes on the FTL side

- Bug fixed: [1463664]kup `[/#noparse]` is printed out

#### 2.3.6

Date of release: 2006-03-15

Quick release that fixes a serious bug of 2.3.5, days after its release. So for the recently added new features please see the section of 2.3.5.

##### Changes on the Java side

- Bug fixed: In FreeMarker 2.3.5 only, when you read a bean property for the second time, FreeMarker will say that it's missing (null).

#### 2.3.5

Date of release: 2006-03-11

This release was withdrawn because of a serious bug in it. Please don't use it! Of course, all new features of it are included in FreeMarker 2.3.6.

A few new features and several bugfixes.

##### Changes on the FTL side

- Bug fixed: [1435847] Alternative syntax doesn't work for comments

- Bug fixed: With the new square bracket syntax, the tag could be closed with `>`. Now it can be closed with `]` only.

- Bug fixed: [1324020] `ParseException` with the `ftl` directive if it wasn't in its own line

- Bug fixed: [1404033] `eval` built-in fails with hash concatenation

##### Changes on the Java side

- A new `Configuration` level setting, `tagSyntax` was added. This determines the syntax of the templates (angle bracket syntax VS square bracket syntax) that has no `ftl` directive in it. So now you can choose to use the new square bracket syntax by default. However, the recommended is to use auto-detection (`yourConfig.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX)`), because that will be the default starting from 2.4. Auto-detection chooses syntax based on the syntax of the first FreeMarker tag of the template (could be any FreeMarker tag, not just `ftl`). Note that as with the previous version, if a the template uses `ftl` directive, then the syntax of the `ftl` directive determines the syntax of the template, and the `tagSyntax` setting is ignored.

- Now `BeansWrapper`, `DefaultObjectWrapper` and `SimpleObjectWrapper` support lookup with 1 character long strings in `Map`-s (like `myHash["a"]`) that use `Character` keys. Simply, as a special case, when a hash lookup fails on a string that is 1 character long, it checks for the `Character` key in the underlying map. (Bug tracker entry [1299045] FreeMarker doesn't support map lookup with Character keys.)

- A new property, `strict` was added to `BeansWrapper`, `DefaultObjectWrapper` and `SimpleObjectWrapper`. If this property is `true` then an attempt to read a bean propertly in the template (like `myBean.aProperty`) that doesn't exist in the bean class (as opposed to just holding `null` value) will cause `InvalidPropertyException`, which can't be suppressed in the template (not even with `myBean.noSuchProperty?default('something')`). This way `?default('something')` and `?exists` and similar built-ins can be used to handle existing properties whose value is `null`, without the risk of hiding typos in the property names. Typos will always cause error. But mind you, it goes against the basic approach of FreeMarker, so use this feature only if you really know what are you doing.

- Bug fixed: [1426227] `NullPointerException` in `printStackTrace(...)`

- Bug fixed: [1386193] Division by zero in `ArithmeticEngine`

#### 2.3.4

Date of release: 2005-10-10

Some new features and bugfixes.

##### Changes on the FTL side

- Now you can use `[` and `]` instead of `<` and `>` for the FreeMarker tags. For example you can write `[#if loggedIn]...[/#if]` and `[@myMacro /]`. More info...

- Bugfix: the `has_content` built-in returned `false` for number, date and boolean values (if the value was not a multi-type value that is also a sequence or collection or hash or string). Now it always returns `true` for a number, date or boolean values (except if the value is also a sequence or collection or hash or string, because then it will be examined only like that).

##### Changes on the Java side

- Bugfix: the parameterless constructor of the `ClassTemplateLoader` didn't worked.

- Bugfix: The Jython wrapper didn't wrapped `java.util.Date` objects well. Now it wraps them with `BeanWrapper` to `TemplateDateModel`.

- Bugfix: the `include` directive was blamed when the included file had syntax error.

##### Other changes

- Minor Manual fixes.

#### 2.3.3

Date of release: 2005-06-23

Some new features and lot of bugfixes.

Attention:

- If you are using the Log4J logging, from now at least Log4J 1.2 is required. This is because of incompatible changes in the Log4J API.

- If you build FreeMarker yourself: from now at least JavaCC 3.2 (instead of JavaCC 2.1) and at least Ant 1.6.1 (instead of Ant 1.5.x) is required. This doesn't affect users who use the `freemarker.jar` comes with the distribution.

##### Changes on the FTL side

- New built-in for formatting numbers for ``computer audience'' as opposed to human audience: `c`. It should be used for numbers that must use Java language formatting regardless of the number format and locale settings, like for a database record ID used as the part of an URL or as invisible field value in a HTML form, or for printing CSS/JavaScript numerical literals.

- New built-in for the columnar/tabular displaying of sequences: `chunk`.

- The sequence slice and substring operators now allow the omitting of the last index, in which case it defaults to the index of the last sequence item or character. Example: `products[2..]`. (Also, numerical range literals now allow the omitting of the final number, in which case it defaults to infinity. Example: `5..`.)

- Bugfix: `?replace` has worked forever if the string to replace was `""`.

##### Changes on the Java side

- New template loader: `freemarker.cache.StringTemplateLoader`. It uses a `Map` with `Strings` as its source of templates. See more in the JavaDoc.

- Experimental Rhino support: FreeMarker now comes with an experimental object wrapper for Rhino (Java ECMAScript implementation): `freemarker.ext.rhino.RhinoWrapper`

- Some new utility methods for `SimpleXxx` classes: `SimpleHash.toMap()`, `SimpleSequence.toList()`.

- Bugfix: FTL literals and any other `SimpleSequnce`-s, and `SimpleHash`-es now can be used as parameters to the FreeMarker-unaware Java methods that are exposed by `DefaultWrapper` or `BeansWrapper`. That is, the method parameters are automatically converted from `TemplateTypeModel`-s to `java.util.Map` and `java.util.List` respectively.

- Bugfix: The JSP support now works in JSP 2 compliant containers as well. No, it doesn't support the new features of JSP 2 yet, it's just that the JSP 1.2 taglib support has not worked in JSP 2 containers.

- Bugfix: The `Configuration.setOutputEncoding` and `setURLEscapingCharset` methods died with `NullPointerException` when you tried to set the setting value to `null`, which is legal for these settings.

- Bugfix: `freemarker.template.utility.StringUtil.replace(...)` has worked forever if the string to replace was `""`.

- Bugfix: The Log4J logging was updated to be compatible with the upcoming Log4J 1.3. Note that now FreeMarker will need at least Log4J 1.2.

- Bugfix: FreeMarker didn't built from the source code on J2SE 1.5, because of the introduction of the `enum` keyword.

- Bugfix: The return value of `SimpleSequence.synchronizedWrapper()` was not properly synchronized. Same with `SimpleHash.synchronizedWrapper()`.

- Bugfix: Problem with `BeansWrapper` and overridden bean methods/properties. (Details: bug-tracker entry #1217661 and #1166533)

- Bugfix: Can't access JSP taglibs if `Request` attribute is defined in the data-model (Details: bug-tracker entry #1202918).

- Bugfix: Various minor parser glitches were fixed.

##### Other changes

- Manual improvements, especially in the FAQ.

#### 2.3.2

Date of release: 2005-01-22

Bugfix release.

##### Changes on the Java side

- Bugfix: If you use JSP taglibs in FreeMarker templates, FreeMarker possibly tried to get DTD-s from the Sun Web site because of a bug introduced with FreeMarker 2.3.1. This was a serious problem since if your server is offline or the Sun Web site becomes temporarily inaccessible the templates that are using JSP taglibs will possibly die with error.

- Bugfix: The `DefaultObjectWrapper` has ignored the value of the `nullModel` property. (Note that it's discouraged to use a ``null model''.)

#### 2.3.1

Date of release: 2005-01-04

Maintenance (with some important new features) and bugfix release.

##### Possible backward compatibility issue

There is a bugfix that may affect the behavior of you Web application if you use JSP tags in FreeMarker templates: FreeMarker's implementation of `javax.servlet.jsp.PageContext.getSession()` was incorrect. The `getSession()` method is a convenience method by which the custom tag can get the current `HttpSession` object (possibly `null` if there is no session). Till now, if the session didn't existed then it has created it automatically, so it never returned `null`. This was a bug, so starting from 2.3.1 it never creates the session, just returns `null` if it doesn't exist. The old incorrect behavior could cause page rendering to fail if the method is called after the page is partially flushed. But beware, the old behavior has possibly hidden some bugs of the Web application, where it forgot to create the session, so with the new correct behavior you may face malfunction caused by previously cloaked bugs of the Web application. (It's the task of the MVC Controller to create the session, except if the JSP tag that needs a session is written so it creates it automatically, but then it doesn't expects that `getSession()` will do it.)

##### Changes on the FTL side

- New built-in: `url`. This built-in can be used for URL escaping. Note, however, that to use this built-in conveniently, the software that encapsulates FreeMarker has to be 2.3.1 aware (programmers will find more info bellow...).

- New special variables: `output_encoding` and `url_escaping_charset`. Note, however, that to use these, the software that encapsulates FreeMarker has to be 2.3.1 aware (programmers will find more info bellow...).

- New built-ins for sequences: `seq_contains`, `seq_index_of`, `seq_last_index_of`.

- New built-ins for strings: `left_pad`, `right_pad` and `contains`.

- New directive: `attempt`/`recover`

- The `js_string` built-in now escapes `>` as `\>` (to avoid `</script>`).

- The `sort` and `sort_by` built-ins now can sort by date values. Also, `sort_by` built-in now can sort by the subvarible of a subvariable of a subvariable... etc. for any level depth. (Details...)

- `freemarker.template.TemplateExceptionHandler.HTML_DEBUG_HANDLER` now prints more HTML-context-proof messages.

##### Changes on the Java side

- New setting: `output_encoding`. This setting is used for informing FreeMarker about the charset that the enclosing software (as a Web application framework) uses for the output of FreeMarker. It's undefined by default, and although it is not strictly required to set it, the enclosing software should do so. This setting must be set if templates want to use the new `output_encoding` special variable, and possibly if they want to use the new `url` built-in. Note that the FreeMarker API allows you to set settings for each template execution individually (look at `Template.createProcessingEnvironment(...)`).

- New setting: `url_escaping_charset`. This is the charset used for calculating the escaped parts (`%XX`) when you do URL escaping with the new `url` built-in. If it is not set, then the `url` built-in uses the value of the `output_encoding` setting, and if that's not set either, then the parameterless version of `url` built-in (`${foo?url}`) can't be used.

- Using the singleton (static) `Configuration` instance is clearly a bad practice, so related methods are now deprecated, and the Manual was adjusted, and the `FreemarkerXmlTask` was updated as well.

- The `freemarker.template.utility.Constants` class was added that contains various static final fields that store frequently used constant `TemplateModel` values, as `EMPTY_SEQUENCE`, `ZERO`, ...etc.

- When using `SecurityManager` with FreeMarker, accessing system properties may caused AccessControlException. Now such exceptions are catched and logged with warning level, and the default value of the property is returned.

- The needles `InvocationTargetException` is now removed from the exception cause trace in certain cases.

- Added a dirty hack that prints `ServletException` root cause in `TemplateException`'s stack trace if that's the direct cause exception of the `TemplateException`, despite the poorly written `ServletException` class.

- Bugfix: FreeMarker's implementation of `javax.servlet.jsp.PageContext.getSession()` was incorrect. The `getSession()` method is a convenience method by which the custom tag can get the current `HttpSession` object (possibly `null` if there is no session). Till now, if the session didn't existed then it has created it automatically, so it never returned `null`. This was a bug, so starting from 2.3.1 it never creates the session, just returns `null` if it doesn't exist. The old incorrect behavior could cause page rendering to fail if the method is called after the page is partially flushed. But beware, the old behavior has possibly hidden some bugs of the Web application, where it forgot to create the session, so with the new correct behavior you may face malfunction caused by previously cloaked bugs of the Web application. (It's the task of the MVC Controller to create the session, except if the JSP tag that needs a session is written so it creates it automatically, but then it doesn't expects that `getSession()` will do it.)

- Bugfix: The `BeansWrapper` didn't always handled properly the case of a Java class having both a public static field and a public static method with the same name.

- Bugfix: `SimpleMethodModel` had incorrectly propagate exceptions sometimes, causing null pointer exception.

- Bugfix: The template execution may used outdated cached values when you have processed the same `Environment` for multiple times, and changed settings between the two processings. Note that this could happen only in single-thread environment, where such setting modifications are allowed.

- Bugfix: Some of the string built-ins has died with `IndexOutOfBounds` exception if the template author has forgotten to specify required parameters. Now they die with more helpful error messages.

- Bugfix: `freemarker.ext.dom.NodeModel.equals(...)` has died with null pointer exception if its argument was `null`.

- Bugfix: The cause exception of `TemplateException`-s was sometimes printed twice in stack traces with J2SE 1.4 or later.

- Bugfix: The `StringUtil.FTLStringLiteralEnc(String)` method was finished.

##### Other changes

- Fixes and improvements in the Manual and in the API JavaDoc.

##### The history of the releases before the final version

###### Differences between the preview release and final release

- Added a dirty hack that prints `ServletException` root cause in `TemplateException`'s stack trace if that's the direct cause exception of the `TemplateException`, despite the poorly written `ServletException` class.

- Bugfix: `freemarker.ext.dom.NodeModel.equals(...)` has died with null pointer exception if its argument was `null`.

- Bugfix: The cause exception of `TemplateException`-s was sometimes printed twice in stack traces with J2SE 1.4 or later.

- More minor improvements in the Manual.

#### 2.3

Date of release: 2004-June-15

FreeMarker 2.3 introduces numerous little new features and quality improvements compared to the 2.2.x series. The most notable improvements are the ability to define functions (methods) in templates, the ability to interpolate variables in string literals, the support for a variable number of macro parameters, and the more intelligent default object wrapper. Although none of the improvements is a drastic change, the 2.3.x series is not backward compatible with the 2.2.x series (see the list below), so you may choose to use it for new projects only.

Probably the most ``loudly promoted'' new feature is the totally redesigned XML wrapper. With the new XML wrapper FreeMarker targets a new application domain, which is similar to the application domain of XSLT: transforming complex XML to whatever textual output. Although this subproject is young, it is definitely usable in practice. See the XML Processing Guide for more details.

##### Non backward-compatible changes!

- Since interpolations (`${...}` and `#{...}`) now work inside string literals, the character sequence `${` and `#{` in string literals are reserved for that. So if you have something like `<#set x = "${foo}">`, then you have to replace it with `<#set x = r"${foo}">` -- beware, escapes such as `\n` will not work in raw (`r`) strings.

- The default (initial) value of the `strict_syntax` setting has been changed from `false` to `true`. When `strict_syntax` is `true`, tags with old syntax as `<include "foo.ftl">` will be considered as static text (so they go to the output as-is, like HTML tags do), and not as FTL tags. Such tags have to be rewritten to `<#include "foo.ftl">`, since only parts that starts with `<#`, `</#`, `<@`, or `</@` count as FTL tags. Or, to recover the old transitional behavior, where both legacy and new tag syntax was recognized, you have to explicitly set `strict_syntax` to `false`: `cfg.setStrictSyntaxMode(false)`. Also, for individual templates you can force the old behavior by starting the template with `<#ftl strict_syntax=false>`. (For more information about why strict syntax is better than old syntax read this...)

- Several classes were moved from the `freemarker.template` package, to the new `freemarker.core` package:

  - "Normal" classes: `ArithmeticEngine`, `Configurable`, `Environment`

  - Exceptions: `InvalidReferenceException`, `NonBooleanException`, `NonNumericalException`, `NonStringException`, `ParseException`, `StopException`

  - Errors: `TokenMgrError`

  The main reason of the splitting of `freemarker.template` package was that the amount of "expert" public classes and interfaces grows too much, as we introduce API-s for third-party tools, such as debugging API.

- `freemarker.template.TemplateMethodModel.exec` now returns `Object` instead of `TemplateModel`.

- White-space stripping is now more aggressive as before: it always removes leading and trailing white-space if the line only contains FTL tags. (Earlier the white-space was not removed if the tag was `<#include ...>` or user-defined directive tag with empty directive syntax as `<@myMacro/>` (or its equivalents: `<@myMacro></@myMacro>` and `<@myMacro></@>`). Now white-space is removed in these cases as well.) Also, white-space sandwiched between two non-outputting elements, such as macro definitions, assignments, imports, or property settings, is now ignored. More information:

- The `function` directive is now used for defining methods. You should replace `function` with `macro` in your old templates. Note, however, that old `function`-s will still work if you don't use the `return` directive in them, and you invoke them with the deprecated the `call` directive.

- The expressions `as`, `in`, and `using` are now keywords in the template language and cannot be used as top-level variable names without square-bracket syntax. If, by some chance, you have top-level variables that use one of these names, you will have to rename them, or use the square-bracket syntax with the `.vars` special variable: `.vars["in"]`.

- The `?new` built-in, as it was implemented, was a security hole. Now, it only allows you to instantiate a java object that implements the `freemarker.template.TemplateModel` interface. If you want the functionality of the `?new` built-in as it existed in prior versions, make available an instance of the `freemarker.template.utility.ObjectConstructor` class to your template. (For example: `myDataModel.put("objConstructor", new ObjectConstructor());`, and then in the template you can do this: `<#assign aList = objConstructor("java.util.ArrayList", 100)>`)

- Changes to the `FreemarkerServlet`:

  - The `FreemarkerServlet` uses `ObjectWrapper.DEFAULT_WRAPPER` by default instead of `ObjectWrapper.BEANS_WRAPPER`. What this means is that, by default, objects of type `java.lang.String`, `java.lang.Number`, `java.util.List`, and `java.util.Map` will be wrapped as `TemplateModels` via the classes `SimpleScalar`, `SimpleNumber`, `SimpleSequence`, and `SimpleHash` respectively. Thus, the java methods on those objects will not be available. The default wrapper implementation in FreeMarker 2.3 automatically knows how to wrap Jython objects, and also wraps `org.w3c.dom.Node` objects into instances of `freemarker.ext.dom.NodeModel`.

  - The `FreemarkerServlet` base implementation no longer deduces the locale used for templates with `HttpRequest.getLocale()`. Rather, it simply delegates to the new protected method, `deduceLocale`. The default implementation of this method simply returns the value of configuration the `locale` setting.

##### Changes on the FTL side

- Interpolation in string literals. For convenience, interpolations are now supported in string literals. For example: `<@message "Hello ${user}!" />` is the same as `<@message "Hello " + user + "!" />`

- Raw string literals: In string literals prefixed with `r`, interpolations and escape sequences will not be interpreted as special tokens. For example: `r"\n${x}"` will be simply interpreted as the character sequence `'\'`, `'n'`, `'$'`, `'{'`, `'x'`, `'}'`, and not as line-feed and the value of the `x` variable.

- Method variables can be defined in FTL, with the `function` directive.

- Support for a variable number of macro parameters. If the last parameter in a macro declaration ends with `...`, all extra parameters passed to the macro will be available via that parameter. For macros called with positional parameters, the parameter will be a sequence. For named parameters, the parameter will be a hash. Note that it all works with the new `function` directive as well.

- A new header parameter, `strip_text`, that removes all top-level text from a template. This is useful for ``include files'' to suppress newlines that separate the macro definitions. See `ftl` directive

- New special variable: `.vars`. This is useful to read top-level variables with square bracket syntax, for example `.vars["name-with-hyphens"]` and `.vars[dynamicName]`.

- `macro` and assignment directives now accept arbitrary destination variable name with quoted syntax. For example: `<#macro "name-with-hyphens">...` or `<#assign "foo bar" = 123>`.

- The `?keys` and `?values` hash built-ins now return sequences. In practical terms this means you can access their sizes or retrieve their subvariables by index, and use all of the sequence built-ins. (Note for the programmers: The `TemplateHashModelEx` interface has not been changed. Your old code will work. See the API documentation to see why.)

- Existence built-ins (`?default`, `?exists`, etc.) are now working with sequence subvariables as well. Read the documentation of the `default` built-in for more information.

- White-space stripping is now more aggressive as before: it always removes leading and trailing white-space if the line only contains FTL tags. (Earlier the white-space was not removed if the tag was `<#include ...>` or user-defined directive tag with empty directive syntax as `<@myMacro/>` (or its equivalents: `<@myMacro></@myMacro>` and `<@myMacro></@>`). Now white-space is removed in these cases as well.) Also, top-level white-space that separates macro definitions and/or assignments is now ignored. More information:

- White-space stripping can be disabled for a single line with the `nt` directive (for No Trim).

- Hashes can be concatenated using the `+` operator. The keys in the hash on the right-hand side take precedence.

- New built-ins for Java and JavaScript string escaping: j_string and js_string

- The `replace` and `split` built-ins now support case-insensitive comparsion and regular expressions (J2SE 1.4+ only), and some other new options. More information can be found here.

- New built-in for regular expression matching (J2SE 1.4+ only): `matches`

- New built-in, `eval`, to evaluate a string as FTL expression. For example `"1+2"?eval` returns the number 3.

- New built-ins for Java and JavaScript string escaping: j_string and js_string

- New special variables to read the value of the locale setting: `locale`, `lang`. See more in the reference...

- New special variable to read the FreeMarker version number: `version`. See more in the reference...

- Tree new directives, `recurse`, `visit` and `fallback`, were introduced to support declarative node-tree processing. These are meant to be used typically (though not exclusively) for processing XML input. Together with this, a new variable type has been introduced, the node type. See the chapter on declarative XML processing for more details.

- The `?new` built-in, as it was implemented, was a security hole. Now, it only allows you to instantiate a java object that implements the `freemarker.template.TemplateModel` interface. If you want the functionality of the `?new` built-in as it existed in prior versions, make available an instance of the `freemarker.template.utility.ObjectConstructor` class to your template. (For example: `myDataModel.put("objConstructor", new ObjectConstructor());`, and then in the template you can do this: `<#assign aList = objConstructor("java.util.ArrayList", 100)>`)

- Variable names can contain `@` anywhere (without using quote-bracket syntax). For example: `<#assign x@@@ = 123>` is valid.

- The expressions `as`, `in`, and `using` are now keywords in the template language and cannot be used as top-level variable names without square-bracket syntax (as `.vars["in"]`).

- New parameter to the `ftl` directive: `attributes`. The value of this attribute is a hash that associates arbitrary attributes (name-value pairs) to the template. The values of the attributes can be of any type (string, number, sequence... etc.). FreeMarker doesn't try to understand the meaning of the attributes. It's up to the application that encapsulates FreeMarker (as a Web application framework). Thus, the set of allowed attributes and their semantic is application (Web application framework) dependent.

- Other minor quality improvements...

##### Changes on the Java side

- Smarter default object wrapping: The default object wrapper is now `freemarker.template.DefaultObjectWrapper`, which falls back on wrapping arbitrary objects as beans using the `freemarker.ext.beans.BeansWrapper`. Also, it will wrap `org.w3c.dom.Node` objects with the new DOM wrapper. Also, it is aware of Jython objects, and will use `freemarker.ext.jython.JythonWrapper` if the object passed in is a Jython object. (We count it as a backward compatible change, since this new object wrapper wraps differently only those objects that the old wrapper was not able to wrap, so it has thrown exception.)

- `freemarker.template.TemplateMethodModel.exec` now returns `Object` instead of `TemplateModel`.

- The default (initial) value of the `strict_syntax` setting has been changed from `false` to `true`. When `strict_syntax` is `true`, tags with old syntax as `<include "foo.ftl">` will be considered as static text (so they go to the output as-is, like HTML tags do), and not as FTL tags. Such tags have to be rewritten to `<#include "foo.ftl">`, since only parts that starts with `<#`, `</#`, `<@`, or `</@` count as FTL tags. Or, to recover the old transitional behavior, where both legacy and new tag syntax was recognized, you have to explicitly set `strict_syntax` to `false`: `cfg.setStrictSyntaxMode(false)`. Also, for individual templates you can force the old behavior by starting the template with `<#ftl strict_syntax=false>`. (For more information about why strict syntax is better than old syntax read this...)

- New `CacheStorage` implementation: `freemarker.cache.MruCacheStorage`. This cache storage implements a two-level Most Recently Used cache. In the first level, items are strongly referenced up to the specified maximum. When the maximum is exceeded, the least recently used item is moved into the second level cache, where they are softly referenced, up to another specified maximum. `freemarker.cache.SoftCachseStorage` and `StrongCachseStorage` are deprected, `MruCachseStorage` is used everywhere instead. The default cache storage is now an `MruCachseStorage` object with 0 strong size, and infinite soft size. `Configuration.setSetting` for `cache_storage` now understands string values as `"strong:200, soft:2000"`.

- For `BeansWrapper` generated models, you can now use the `${obj.method(args)}` syntax to invoke methods whose return type is `void`. `void` methods now return `TemplateModel.NOTHING` as their return value.

- `freemarker.template.SimpleHash` now can wrap read-only `Map`-s, such as the map of HTTP request parameters in Servlet API.

- The `TemplateNodeModel` interface was introduced to support recursive processing of trees of nodes. Typically, this will be used in relation to XML.

- New package: `freemarker.ext.dom`. This contains the new XML wrapper, that supports the processing of XML documents using the visitor pattern (i.e. with `<#visit ...>` and similar directives), and to provide more convenient XML traversing as the legacy wrapper. See the XML processing guide for more details.

- New package: `freemarker.core`. Classes used by mostly power-users was moved here from the `freemarker.template` package. The main reason of the splitting of `freemarker.template` package was that the amount of "expert" public classes and interfaces grows too much, as we introduce API-s for third-party tools, such as debugging API.

- New package: `freemarker.debug`. This provides a debugging API, by which you can debug executing templates through network (RMI). You have to write the front-end (client), as the API is just the server side. For more information please read the JavaDoc of the `freemarker.debug` package.

- You can query the FreeMarker version number with static method `Configuration.getVersionNumber()`. Also, the `Manifest.mf` included in `freemarker.jar` now contains the FreeMarker version number, furthermore, executing it with `java -jar freemarker.jar` will print the version number to the stdout.

- Added a new protected `FreemarkerServlet` method: `Configuration getConfiguration()`.

- Date support is now labeled as final. (It was experimental earlier.)

- The `BeansWrapper` has been improved to prevent some security exceptions when introspecting.

- Other minor quality improvements and extensions...

##### Other changes

- Fixes and improvements in the Manual and in the API JavaDoc.

##### The history of the releases before the final version

###### Differences between the final release and Release Candidate 4

- Added a new special variable to print the FreeMarker version number: `version`. See more in the reference...

- Minor documentation fixes and improvements.

###### Differences between the Release Candidate 4 and Release Candidate 3

- The `BeansWrapper` has been improved to prevent some security exceptions when introspecting.

- The `FreemarkerXmlTask` has two new sub-tasks that can be used to prepare template execution with Jython scripts: `prepareModel` and `prepareEnvironment`. The `jython` sub-task is now deprecated, and does the same as `prepareEnvironment`. See the Java API documentation for more details.

- New special variable to read the FreeMarker version number: `version`. See more in the reference...

- Bugfix: Greater-than sign doesn't confuse the `eval` built-in anymore.

- Bugfix: The `BeansWrapper` now wrapps the `null` return values of methods appropriately.

- Bugfix: The `FreemarkerXmlTask` doesn't need Jython classes anymore, unless you really use Jython scripts. Several other bugfixes in the Jython related features.

- Bugfix: If the template exception handler has ignored the exception, errors occurring in interpolations inside FTL tags (e.g. `<#if "foo${badVar}" != "foobar">`) were handled in the same way as errors occuring in interpolations outside FTL tags. Thus, the directive call was not skipped, and the problematic interpolation was replaced with an empty string. (This was inconsistent with the behavior of `<#if "foo"+badVar != "foobar">`, which should be 100% equivalent with the previous example.)

- Bugfix: The `FileTemplateLoader` is now more robust when it receives paths that are malformed according the native file system. In the earlier version such paths sometimes caused unexpected `IOException` that aborted the searching for the template in further `FileTemplateLoader`-s when you use the `MultiTemplateLoader`.

###### Differences between the Release Candidate 3 and Release Candidate 2

- Bugfix: Fixing a fatal bug in the template cache that was introduced with the latest cache ``bugfix''. The template cache has always reloaded the unchanged template when the update delay has been elapsed, until the template has been actually changed, in which case it has never reloaded the template anymore.

###### Differences between the Release Candidate 2 and Release Candidate 1

- Bugfix: The template cache didn't reload the template when it was replaced with an older version.

- API JavaDoc fix: date/time related classes/interfaces were marked as experimental. They are not experimental.

- Minor site improvements.

###### Differences between the Release Candidate 1 and Preview 16 releases

- Warning! Non-backward-compatible change! The default (initial) value of the `strict_syntax` setting has been changed from `false` to `true`. When `strict_syntax` is `true`, tags with old syntax as `<include "foo.ftl">` will be considered as static text (so they go to the output as-is, like HTML tags do), and not as FTL tags. Such tags have to be rewritten to `<#include "foo.ftl">`, since only parts that starts with `<#`, `</#`, `<@`, or `</@` count as FTL tags. Or, to recover the old transitional behavior, where both legacy and new tag syntax was recognized, you have to explicitly set `strict_syntax` to `false`: `cfg.setStrictSyntaxMode(false)`. Also, for individual templates you can force the old behavior by starting the template with `<#ftl strict_syntax=false>`. (For more information about why strict syntax is better than old syntax read this...)

- New parameter to the `ftl` directive: `attributes`. The value of this attribute is a hash that associates arbitrary attributes (name-value pairs) to the template. The values of the attributes can be of any type (string, number, sequence... etc.). FreeMarker doesn't try to understand the meaning of the attributes. It's up to the application that encapsulates FreeMarker (as a Web application framework). Thus, the set of allowed attributes and their semantic is application (Web application framework) dependent.

- Bugfix: `freemarker.template.utility.DeepUnwrap` unwrapped sequences to empty `ArrayList`-s.

- Bugfix: If you included/imported a template with `*/` in path (acquisition), and that template in turn itself included/imported another template with `*/` in path, it may failed.

- New methods to the `freemarker.core.Environment`: `importLib(Template loadedTemplate, java.lang.String namespace)`, `getTemplateForImporting(...)`, `getTemplateForInclusion(...)`.

- Improvements in the `java.io.IOException` related error messages of the `include` and `import` directives.

- Minor improvements in the documentation.

###### Differences between the Preview 16 and Preview 15 releases

- New package: `freemarker.debug`. This provides a debugging API, by which you can debug executing templates through network (RMI). You have to write the front-end (client), as the API is just the server side. For more information please read the JavaDoc of the `freemarker.debug` package. (The debugging API is present for a while, just I forgot to announce it in the version history. Sorry for that.)

- Bugfix: With the new XML wrapper, `@@markup` and similar special keys:

  - have returned `<foo></foo>` for empty elements instead of `<foo />`. Other than it was needlessly verbose, it has confused browsers if you generate HTML.

  - have showed the attributes that have no explicitly given value in the original document, just a default value coming form the DTD.

  - have forgot to put space before the system identifier in the `<!DOCTYPE ...>`.

- Bugfix: XPath with Jaxen has died with `NullPointerException` if the context was an empty node set.

- A bit more intelligent Xalan XPath error messages.

- Revoked fallback-to-classloader logic from the template cache.

- From now, if no XPath engine is available, and the hash key in an ``XML query'' can't be interpreted without XPath, an error will tell this clearly, rather than silently returning undefined variable (null).

- Bugfix: Some templates have caused the parser to die.

- Some other minor improvements here and there...

###### Differences between the Preview 15 and Preview 14 releases

- Bugfix: The new default template cache storage (`MruCacheStorage`) has started to continually fail with `NullPointerException` from a random point of time, usually when the memory usage was high in the JVM.

- Bugfix: In error messages, when the quoted FTL directive had nested content, that was quoted as well, so the quotation could be very long and expose nested lines needlessly.

###### Differences between the Preview 14 and Preview 13 releases

- `freemarker.template.TemplateMethodModel.exec` now returns `Object` instead of `TemplateModel`.

- Fixes and improvements for XPath with Jaxen (not Xalan). Non-node-set XPath expressions are now working. FreeMarker variables are accessible in XPath expressions with XPath variable references (e.g. `doc["book/chapter[title=$currentTitle]"]`).

- `freemarker.cache.SoftCachseStorage` and `StrongCachseStorage` is deprected. The more flexible `MruCachseStorage` is used instead everywhere. The default cache storage is now an `MruCachseStorage` object with 0 strong size, and infinite soft size. `Configuration.setSetting` for `cache_storage` now understands string values as `"strong:200, soft:2000"`.

- Bugfix: `freemarker.cache.MruCachseStorage` has died with `ClassCastException` sometimes.

- New built-ins for Java and JavaScript string escaping: j_string and js_string

- `freemarker.template.TemplateExceptionHandler.HTML_DEBUG_HANDLER` now prints more HTML-context-proof messages.

- You can query the FreeMarker version number with static method `Configuration.getVersionNumber()`. Also, the `Manifest.mf` included in `freemarker.jar` now contains the FreeMarker version number, furthermore, executing it with `java -jar freemarker.jar` will print the version number to the stdout.

- Added a new protected `FreemarkerServlet` method: `Configuration getConfiguration()`.

- Bugfix: FreeMarker has frozen on empty conditional blocks in certain contexts.

- Bugfix: Methods called twice on an object using the `list` directive, as `parent.getChildren()` with `<#list parent.children as child> ...</#list>`

###### Differences between the Preview 13 and Preview 12 releases

- White-space stripping is now more aggressive as before: it always removes leading and trailing white-space if the line only contains FTL tags. (Earlier the white-space was not removed if the tag was `<#include ...>` or user-defined directive tag with empty directive syntax as `<@myMacro/>` (or its equivalents: `<@myMacro></@myMacro>` and `<@myMacro></@>`). Now white-space is removed in these cases as well.) Also, top-level white-space that separates macro definitions and/or assignments is now ignored. More information:

- White-space stripping can be disabled for a single line with the `nt` directive (for No Trim).

- A new directive for the declarative XML processing: `fallback`

- `freemarker.template.SimpleHash` now can wrap read-only `Map`-s, such as the map of HTTP request parameters in Servlet API.

###### Differences between the Preview 12 and Preview 11 releases

The only change between this and the previous preview release is that Preview 11 had a bug where DOM trees would never be garbage-collected.

###### Differences between the Preview 11 and Preview 10 releases

- Many XML related changes. Some of them are incompatible with the previous preview releases! For a more detailed explanation of how XML related features now work, see:

  - Attention! Attribute queries such as `foo.@bar` now return sequences (similarly to child element queries and XPath queries), not single nodes. Because of the rule with node sequences of size 1, it is still good to write `${foo.@bar}`, but built-ins such as `?exists`, `?if_exists` or `?default` don't work as before. For example, instead of `foo.@bar?default('black')`, you now have to write `foo.@bar[0]?default('black')`. So if you have used existence built-ins with attributes, you have to find those occurrences in the templates and add that `[0]`.

  - Attention! XML name-space handling has been totally reworked and is absolutely incompatible with pre 10. Don't worry about this if none of your XML input documents use you use `xmlns` attributes. Worry, though, if you have utilized the ``loose mode'', where only the local name of elements were compared, because that's now gone. Sorry...

  - Attention! Special-keys `@@` and `@*` now return a sequence of attribute nodes instead of the hash of them.

  - Several hash keys are now working for node sequences that store multiple nodes. For example, to get the list of all `para` elements of all `chapter`-s, just write `doc.book.chapter.para`. Or, to get list of title attributes of all `chapter`-s write `doc.book.chapter.@title`.

  - New special hash keys: `**`, `@@start_tag`, `@@end_tag`, `@@attribute_markup`, `@@text`, `@@qname`.

  - `?parent` for attribute nodes now returns the element node the attribute node belongs to.

  - You can use Jaxen instead of Xalan for XPath expressions, if you call the static `freemarker.ext.dom.NodeModel.useJaxenXPathSupport()` method once. We plan to use Jaxen automatically instead of Xalan if it is available, just the Jaxen support is not fully functional yet.

- New special variable: `.vars`. This is useful to read top-level variables with square bracket syntax, for example `.vars["name-with-hyphens"]` and `.vars[dynamicName]`.

- New built-in, `eval`, to evaluate a string as FTL expression. For example `"1+2"?eval` returns the number 3.

- `FreemarkerServlet` now uses the configuration's `locale` setting, rather than `Locale.getDefault()`, to set the locale of the templates. Also, the signature of the `deduceLocale` method has been changed.

- We have a new (beta status) `CacheStorage` implementation: `freemarker.cache.MruCacheStorage`. This cache storage implements a two-level Most Recently Used cache. In the first level, items are strongly referenced up to the specified maximum. When the maximum is exceeded, the least recently used item is moved into the second level cache, where they are softly referenced, up to another specified maximum. You can plug to try it with `cfg.setCacheStorage(new freemarker.cache.MruCacheStorage(maxStrongSize, maxSoftSize))`.

###### Differences between the Preview 10 and Preview 9 releases

- The special key `@@xmlns` was removed in favor of a new FTL directive for the same purpose, `<#xmlns...>`.

- By default, the system is stricter about the use of namespace prefixes. In general, you must use a prefix to qualify subelements that are associated with an XML nampespace. You can do this with the new `<#xmlns...>` directive, but prefixes declared in the input XML doc will actually work with no declaration.

- Introduced a new special key called `@@text` that returns all the text nodes contained (recursively) in an element all concatenated together.

- Either Jaxen or Xalan can be used to provide XPath functionality. Prior versions only worked with Xalan.

- The `FreemarkerServlet` uses `ObjectWrapper.DEFAULT_WRAPPER` by default instead of `ObjectWrapper.BEANS_WRAPPER`. What this means is that, by default, objects of type `java.lang.String`, `java.lang.Number`, `java.util.List`, and `java.util.Map` will be wrapped as `TemplateModels` via the classes `SimpleScalar`, `SimpleNumber`, `SimpleSequence`, and `SimpleHash` respectively. Thus, the java methods on those objects will not be available. The default wrapper implementation in FreeMarker 2.3 automatically knows how to wrap Jython objects, and also wraps `org.w3c.dom.Node` objects into instances of `freemarker.ext.dom.NodeModel`.

- The `FreemarkerServlet` base implementation no longer deduces the locale to use from the HttpRequest.getLocale() hook. Rather, it simply delegates to a `deduceLocale()` hook that is overridable in subclasses. The base implementation simply uses `Locale.getDefault()`

###### Differences between the Preview 9 and Preview 8 releases

- Fixed bugs introduced with Preview 8: XPath, `@@markup` and `@@nested_markup` now works with the document node.

###### Differences between the Preview 8 and Preview 7 releases

- `macro` and assignment directives now accept arbitrary destination variable name with quoted syntax. For example: `<#macro "foo-bar">...` or `<#assign "this+that" = 123>`. This is important, because XML element names can contain hyphen, and it was not possible to define a handler macro for those elements, till now.

- Special key `@@content` was renamed to `@@nested_markup`.

- Fixed outdated XML related Manual parts (that were outdated even in Preview 7).

- Better parse-error messages.

- Minor bugfixes here and there...

###### Differences between the Preview 7 and Preview 6 releases

- Caching of XPath queries should lead to significant performance improvements for XML processing, at least when XPath is heavily used.

- Refinements in handling of XML namespaces in the XML processing functionality. The new `strict_namespace_handling` setting introduced in 2.3pre6 was removed. A general-purpose solution was arrived at that should make that configuration setting unnecessary.

- Special key `@xmlns` was renamed to @@xmlns. Reserved namespace prefix `default` was renamed to `@@default`.

- The `ftl` directive now accepts non-string types.

- New special keys were introduced for XML node wrappers in the freemarker.ext.dom package. The `@@markup` key returns the literal markup that make up that element and the `@@content` key returns all the element's markup excluding the opening and closing tags.

- Minor bugfixes here and there...

###### Differences between the Preview 6 and Preview 5 releases

- Existence built-ins (`?default`, `?exists`, etc.) now work with sequence subvariables as well. Read the documentation of the `default` built-in for more information.

- The `matches` built-in now returns a sequence instead of a collection.

- Refinements in handling of XML namespaces in the XML processing functionality. A new setting, `strict_namespace_handling` was introduced. If this is set (it is off by default) any node-handling macro used in with the visit/recurse machinery must be from a macro library that declares in its ftl header that it handles the namespace in question.

- Minor bugfixes here and there...

###### Differences between the Preview 5 and Preview 4 releases

- The `replace` and `split` built-ins now support case-insensitive comparison and regular expressions (J2SE 1.4+ only), and some other new options. More information can be found here.

- New butilt-in for regular expression matching (J2SE 1.4+ only): `matches`

- Minor bugfixes here and there...

- Manual: More browser-safe HTML-s. More updated content.

###### Differences between the Preview 4 and Preview 3 releases

- Bugfix: with multi-type variables, `+` operator overload for hash type had higher precedence than the precedence of some older overloads.

- The API documentation was missing from the distribution `tar.gz`.

###### Differences between the Preview 3 and Preview 2 releases

- XML processing: Many various bugfixes, especially with the declarative processing.

- XML processing: the `namespace_uri` built-in, the `xmlnsuri` header parameter, and the `TemplateNodeModel.getNodeNamespace` method were renamed to `node_namespace` and `getNodeNamespace` respectively.

- XML processing: Better documentation. Especially, note:

- A new header parameter, `strip_text`, that removes all top-level text from a template. See `ftl` directive

- Support for a variable number of macro parameters. If the last parameter in a macro declaration ends with `...`, all extra parameters passed to the macro will be available via that parameter. For macros called with positional parameters, the parameter will be a sequence. For named parameters, the parameter will be a hash.

- For `BeansWrapper` generated models, you can now use the `${obj.method(args)}` syntax to invoke methods whose return type is `void`. `void` methods now return `TemplateModel.NOTHING` as their return value.

###### Differences between the Preview 2 and Preview 1 releases

- The `freemarker.ext.dom.NodeModel` API changed slightly. The `setDocumentBuilder()` method was changed to `setDocumentBuilderFactory()` because the older scheme was not thread-safe. The `stripComments` and `stripPIs` methods are renamed to The `removeComments` and `removePIs`, and are fixed now. A new method, `simplify` has been added.

- The expressions `as`, `in`, and `using` are now keywords in the template language and cannot be used as top-level variable names without square-bracket syntax (as `.vars["in"]`). If, by some chance, you have top-level variables that use one of these names, you will have to rename them (or use the square-bracket syntax). Sorry for the inconvenience.

- The `?new` built-in, as it was implemented, was a security hole. Now, it only allows you to instantiate a java object that implements the `freemarker.template.TemplateModel` interface. If you want the functionality of the `?new` built-in as it existed in prior versions, make available an instance of the new `freemarker.template.utility.ObjectConstructor` class to your template.

- The `<#recurse>` directive was broken. It did not work with a `using` clause. This is now fixed.

#### 2.2.8

Date of release: 2004-June-15

Bugfix and maintenance release.

##### Changes on the FTL side

- Added a new special variable to print the FreeMarker version number: `version`. See more in the reference...

##### Changes on the Java side

- The `BeansWrapper` has been improved to prevent some security exceptions when introspecting.

- Bugfix: The `FileTemplateLoader` is now more robust when it receives paths that are malformed according the native file system. In the earlier version such paths sometimes caused unexpected `IOException` that aborted the searching for the template in further `FileTemplateLoader`-s when you use the `MultiTemplateLoader`.

- Some parts of the FreeMarker code has been marked as privileged code section, so you can grant extra privileges to FreeMarker when you use a security manager (this is a backporting from 2.3). See more here...

##### Other changes

- Minor documentation fixes and improvements.

#### 2.2.7

Date of release: 2004-March-17

Important bugfix release.

##### Changes on the Java side

- Bugfix: Fixing a fatal bug in the template cache that was introduced with the latest cache ``bugfix''. The template cache has always reloaded the unchanged template when the update delay has been elapsed, until the template has been actually changed, in which case it has never reloaded the template anymore.

#### 2.2.6

Date of release: 2004-March-13

Maintenance and bugfix release. Some of improvements are back-portings from FreeMarker 2.3rc1.

##### Changes on the FTL side

- New special variable: `.vars`. This is useful to read top-level variables with square bracket syntax, for example `.vars["name-with-hyphens"]` and `.vars[dynamicName]`.

- New built-ins for Java and JavaScript string escaping: j_string and js_string

##### Changes on the Java side

- Bugfix: The template cache didn't reload the template when it was replaced with an older version.

- Bugfix: `freemarker.template.utility.DeepUnwrap` unwrapped sequences to empty `ArrayList`-s.

- Bugfix: In error messages, when the quoted FTL directive had nested content, that was quoted as well, so the quotation could be very long and expose nested lines needlessly.

- `freemarker.template.TemplateExceptionHandler.HTML_DEBUG_HANDLER` now prints more HTML-context-proof messages.

- You can query the FreeMarker version number with static method `Configuration.getVersionNumber()`. Also, the `Manifest.mf` included in `freemarker.jar` now contains the FreeMarker version number, furthermore, executing it with `java -jar freemarker.jar` will print the version number to the stdout.

- Date support is now labeled as final. (It was experimental earlier.) There was no change since FreeMarker 2.2.1.

##### Other changes

- Fixes and improvements in the Manual and in the API JavaDoc. The documentation now works with the Eclipse help plugin (accessible in the ``Editor/IDE plugins'' section of the FreeMarker Web page).

- Minor site improvements.

#### 2.2.5

Date of release: 2003-09-19

Maintenance and bugfix release.

##### Changes on the Java side

- Creating a `Configuration` instance using the default constructor no longer fails if the current directory is unreadable due to I/O problems, lack of security permissions, or any other exception.

#### 2.2.4

Date of release: 2003-09-03

Maintenance and bugfix release.

##### Changes on the Java side

- Improvements to JSP taglib support. If some third party taglib didn't work for you with FreeMarker, maybe now it will.

  - The JSP `PageContext` now implements `forward` and `include` methods.

  - Accepting `EVAL_PAGE` as an alias to `SKIP_BODY` in return values from `doStartTag`. It's a common bug in some widespread tag libraries, and now FreeMarker is less strict and accepts it.

- Fixes for some rare problems regarding namespaces of macros.

##### Other changes

- Minor improvements to the documentation.

#### 2.2.3

Date of release: 2003-07-19

Bugfix release.

##### Changes on the FTL side

- Added the `is_date` built-in.

- Bugfix: Various `is_xxx` built-ins were returning `false` when applied to undefined expressions. Now they correctly fail on them.

##### Changes on the Java side

- Bugfix: The JSP taglib support can now read JSP 1.2 compliant TLD XML files.

- Bugfix: The JSP taglib support now emits more helpful exception messages when the specified TLD XML file is not found (previously it threw a `NullPointerException`).

- Bugfix: The JSP taglib support now initializes a custom tag after its parent and page context is set as some tags expect them to be set when attribute setters are called.

- Bugfix: The `BeansWrapper` could fail to analyze classes under very rare circumstances due to a premature storage optimization.

#### 2.2.2

Date of release: 2003-05-02

Bugfix release.

##### Changes on the Java side

- Bugfix: The `_text` key of the `freemarker.ext.xml.NodeListModel` was not returning the text of the element when used with W3C DOM trees.

- The classes are now built against JDK 1.2.2 classes, ensuring the binary compatibility of FreeMarker distribution with JDK 1.2.

#### 2.2.1

Date of release: 2003-04-11

This version introduces important new features, such as the native FTL date/time type, and the auto-include and auto-import settings.

The date/time support is experimental, but we hope it will not substantially change. We would like to label it as final ASAP, so we urge everybody to send feedback on this topic to the mailing lists.

##### Changes on the FTL side

- New scalar type: date. For more information read: , , interpolation, ?string built-in for dates

##### Changes on the Java side

- New `TemplateModel` subinterface: `TemplateDateModel`. For more information read

- auto-include and auto-import: With these new configuration level settings, you can include and import commonly used templates (usually collection of macro definitions) at the top of all templates, without actually typing `<#include ...>` or `<#import ...>` into the templates again and again. For more information please read the Java API documentation of `Configuration`

- New template method: `createProcessingEnvironment`. This method makes it possible for you to do some special initialization on the `Environment` before template processing, or to read the environment after template processing. For more information please read the Java API documentation.

- Changes to `freemarker.ext.beans` package: `BeanModel`, `MapModel`, and `ResourceModel` now implement `TemplateHashModelEx`.

- Bugfix: `Configurable.setSettings(Properties)` didn't removed redundant spaces/tabs at the end of property values.

#### 2.2

Date of release: 2003-03-27

This release introduces some really important new features. Unfortunately, evolution was painful again; we have a few non-backward compatible changes (see below). Also, for those of you awaiting desired native date/time type, sorry, it is still not here (because of some internal chaos in the team... stand by, it's coming).

##### Non backward-compatible changes!

- Macros are now plain variables. This means that if you are unlucky and you have both a macro and another variable with the same name, now the variable will overwrite the macro, so your old template will malfunction. If you have a collection of common macros, you should use the new namespace feature to prevent accidental clashes with the variables used in the templates.

- With the introduction of the new namespace support, `global` and `assign` directives are no longer synonyms. `assign` creates a variable in the current `namespace`, while `global` creates variable that is visible from all namespaces (as if the variable would be in the data-model). Thus, the variable created with `assign` is more specific, and hides the variable of the same name created with `global`. As a result, if you use both `global` and `assign` mixed for the same variable in your templates, now they will malfunction. The solution is to search-and-replace all `global`s in your old templates with `assign`.

- The reserved hash `root` no longer exists as a predefined variable (we no longer have reserved variables). Use special variable expressions to achieve similar effects. However, we have no equivalent replacement for `root` because of the changes in the variable scopes caused by the introduction of namespaces. You may should use `.globals` or `.namespace`.

- The `BeansWrapper` no longer exposes native Java arrays, booleans, numbers, enumerations, iterators, and resource bundles as `TemplateScalarModel`. This way, number objects wrapped through `BeansWrapper` are subject to FreeMarker's number formatting machinery. Also, booleans can be formatted using the `?string` built-in.

- The signature of `Configuration.setServletContextForTemplateLoading` has been changed: the first parameter is now `Object` instead of `javax.servlet.ServletContext`. Thus, you have to recompile your classes that call this method. The change was required to prevent class-loading failure when `javax.servlet` classes are not available and you would not call this method.

- This release introduces a parse-time white-space remover that strips some of the typical superfluous white-space around FreeMarker tags and comments. This feature is on by default! Most probably this will not cause problems if you generate white-space neutral output like HTML. But if it does cause undesirable reformatting in output you generate, you can disable it with `config.setWhitespaceStripping(false)`. Also, you can enable/disable it on a per-template basis with the new `ftl` directive.

- Some new directives were introduced: `nested`, `import`, `escape`, `noescape`, `t`, `rt`, `lt`. This means that if you are unlucky and the text of your template contains something like `<nested>`, then that will be misinterpreted as a directive. To prevent this kind of problem in the future, we recommend everybody to switch from the old syntax to the new syntax (``strict syntax''). The strict syntax will be the the default syntax starting from some of the later releases anyway. We plan to release a conversion tool for converting old templates. For more information please read:

- The data-model created by the `FreemarkerServlet` now uses automatic scope discovery, so writing `Application.attrName`, `Session.attrName`, `Request.attrName` is no longer mandatory; it's enough to write `attrName` (for more information read this). This may break an old template if that rely on the non-existence of certain top-level variables.

- `FreemarkerServlet` now uses the encoding of the template file for the output, unless you specify the encoding in the `ContentType` init-param, such as `text/html; charset=UTF-8`.

- The format of template paths is now more restricted than before. The path must not use `/`, `./` and `../` and `://` with other meaning as they have in URL paths (or in UN*X paths). The characters `*` and `?` are reserved. Also, the template loader must not want paths starting with `/`. For more information please read:

- Till now `TemplateTransformModel.getWriter` has received null as parameter map if the transform was called without parameters. From now, it will receive an empty Map instead. Note that the previous API documentation didn't state that it always receives null if there are no parameters, so hopelessly only very few classes exploit this design mistake.

##### Changes in FTL (FreeMarker Template Language)

- User-defined directives: Transform and macro call syntax has been unified; they can be called in the same way, as user-defined directives. This also means that macros support named parameters and nested content (like the -- now deprecated -- `transform` directive did). For example, if you have a macro called `sect`, you may call it via `<@sect title="Blah" style="modern">Blah blah...</@sect>`. For more information read:

- Macros are now plain variables. This significantly simplifies FreeMarker semantics, while providing more flexibility; for example you can pass macros as parameters to other macros and transforms. As for the problem of clashing commonly-used-macro and variable names, we provide a more powerful solution: namespaces.

- Namespaces: Names-spaces are invaluable if you want to assemble collections (``libraries'') of macros and transforms (and other variables), and then use them in any template without worrying about accidental name clashes with the application specific and temporary variables, or with the variables of other collections you want to use in the same template. This is extremely important if FreeMarker users want to share their macro/transform collections. For more information read:

- With the introduction of namespaces our variable related terminology changed. As a result, `assign` is no longer synonymous with `global`. The `assign` directive has been undeprecated, and should be used instead of `global` almost everywhere. In the new approach `assign` creates variables in the current namespace, while `global` creates a variable that is visible from all namespaces (as if the variable were in the root of the data-model). A variable created with `assign` in the current namespace hides the variable of the same name that was created with `global`.

- `ftl` directive: With this directive you can give information about the template for FreeMarker, like the encoding (charset) of the template, the used FTL syntax variant, etc. Also, this directive helps you to write templates that are less dependent on FreeMarker configuration settings, also it helps third-party tools to identify and correctly parse FreeMarker templates. For more information see: `ftl` directive

- White-space stripping: FreeMarker now automatically removes some of the typical superfluous white-spaces around FreeMarker tags and comments, like the indentation spaces before- and line-break after `<#if ...>` tags. For more information read:

- New directive to apply a common ("escaping") expression to all interpolations in a block: `escape`. The name comes from the common usage of this directive for automatic HTML-escaping of interpolations.

- The new and preferred way of number formatting with `string` built-in is `foo?string(format)`, instead of the less natural `foo?string[format]`.

- The `string` built-in works for boolean values. For example: `${spamFilter?string("enabled", "disabled")}`. For more information read the reference.

- The default strings for outputting boolean value using the `string` built-in can be set using the `boolean_format` setting.

- Comments can be placed inside FTL tags and interpolations. For example: `<#assign <#-- a comment --> x = 3>`

- All letters and numbers are enabled in variable names, also `$` is allowed (as in Java programming language). Thus you can use accents, Arabic letters, Chinese letters, etc.

- String literals can be quoted with apostrophe-quote. `"foo"` and `'foo'` are equivalent.

- New string built-ins: `index_of`, `last_index_of`, `starts_with`, `ends_with`, `replace`, `split`, `chop_linebreak`, `uncap_first`.

- New sequence built-ins: `sort`, `sort_by`.

- New built-ins for experts to check the type of a variable. See: `is_...` built-ins

- New built-in for experts to create a variable of certain Java `TemplateModel` implementation. See: `new` built-in

- New built-in, `namespace`, to get the namespace of a macro.

- New expression type: special variable expression. To prevent backward compatibility problems when we introduce new predefined variables, from now special variable expressions are used to access them.

- New directives: `t`, `rt` and `lt` directives allow you to do explicit white-space removal in extreme FTL applications. For more information read the reference.

- `assign`, `local` and `global` now can capture the output generated be the nested template fragment into the variable. This deprecates `capture_output` transform. More information: assign directive reference

- Bulk assignments (as `<#assign x=1, y=2, z=3>`) no longer need colon to separate the assignments (as `<#assign x=1 y=2 z=3>`), although it is still allowed to preserve backward compatibility.

- Path that contains `//:` is considered as absolute path.

- `include` and `transform` directives no longer need a semicolon to separate the template or transform name from the parameter list, although it is still allowed to preserve backward compatibility.

- `#`-less tag syntax is deprecated (but still working). That is, you should write `<#directive ...>` instead of `<directive ...>`, and `</#directive ...>` instead of `</directive ...>`. For more info read:

- `foreach` is depreciated (but still working). Use `list` instead.

- Bugfix: Undefined variables in hash and sequence constructors (as `[a, b, c]`) didn't caused errors.

- Bugfix: String concatenation had performance problem if there was multiple concatenations chained, as: `"a"+x+"a"+x+"a"+x+"a"+x+"a"+x`.

##### Changes on the Java side

- Arbitrary JSP custom tags can be used as FreeMarker transforms in `FreemarkerServlet`-driven templates. More information:

- Various improvements for `BeansWrapper`:

  - The `BeansWrapper` no longer exposes arbitrary objects as `TemplateScalarModel`s, only `java.lang.String` and `Character` objects. This way, number objects wrapped through `BeansWrapper` are subject to FreeMarker's number formatting machinery. As a side effect, non-string and non-number objects that were previously accepted in equality and inequality operations (because they had a string representation) will now cause the engine to throw exception on comparison attempt.

  - `java.lang.Character` objects are exposed as scalars through `BeansWrapper`.

  - Experimental feature: With the `setSimpleMapWrapper` method of `BeansWrapper` you can configure it to wrap `java.util.Map`-s as `TemplateHashModelEx`-s, and do not expose the methods of the object.

- `TransformControl` interface (was experimental earlier): If the `Writer` returned by `TemplateTransformModel.getWriter` implements this interface, it can instruct the engine to skip or to repeat evaluation of the nested content, and gets notified about exceptions that are thrown during the nested content evaluation. Note that the `onStart` and `afterBody` methods now are allowed to throw `IOException`. For more information please read the API documentation.

- Localized lookup can be disabled with the new `Configuration` methods: `set/getLocalizedLookup`, `clearTemplateCache`

- The new interface `freemarker.cache.CacheStorage` allows users to plug custom template caching strategies with the `cache_storage` setting. The core package now ships with two implementations: `SoftCacheStorage` and `StrongCacheStorage`. For more information read:

- You can set settings with string name and string value with the new `setSetting(String key, String value)` method of `Configurable` super-classes (as `Configuration`). Also you can load settings from `.properties` file with the `setSettings` method.

- Other new `Configuration` methods: `clearTemplateCache`, `clearSharedVariables`, `getTemplateLoader`, and `clone`.

- Changes to `TemplateTransformModel` interface: `getWriter` can throw `IOException`, and can return `null` if the transform does not support body content.

- Till now `TemplateTransformModel.getWriter` has received null as parameter map if the transform was called without parameters. From now, it will receive an empty Map instead. Note that the previous API documentation didn't state that it always receives null if there are no parameters, so hopelessly only very few classes exploit this design mistake.

- Various improvements for `FreemarkerServlet`:

  - The data-model now uses automatic scope discovery, so writing `Application.attrName`, `Session.attrName`, `Request.attrName` is no longer mandatory; it's enough to write `attrName`. For more information read this.

  - `FreemarkerServlet` now uses the encoding of the template file for the output, unless you specify the encoding in the `ContentType` init-param, such as `text/html; charset=UTF-8`.

  - All `Configuration` level settings can by set with Servlet init-params (`template_exception_handler`, `locale`, `number_format`, etc.).

  - The object wrapper the servlet internally uses is now set as the default object wrapper for its `Configuration` instance.

  - It no longer forces session creation for requests that don't belong to an existing session, improving scalability.

- JDOM independent XML-wrapping: `freemarker.ext.xml.NodeListModel` is a re-implementation of `freemarker.ext.jdom.NodeListModel` that does not rely on JDOM; you don't need JDOM .jar anymore. The new `NodeListModel` automatically uses W3C DOM, dom4j, or JDOM, depending on which library is available (that is, depending on what object do you pass to its constructor).

- Bugfix: `WebappTemplateLoader`: Template updating didn't worked correctly with Tomcat due the caching of resources. Now `WebappTemplateLoader` tries to access the resources directly as `File`, if it is possible, thus bypasses the caching.

- Various bug-fixes for `FreemarkerServlet`:

  - The servlet now loads the correct template if it was called through `RequestDispatcher.include`.

  - The caching of `HttpServletRequest` objects is now compliant with the servlet specification.

  - `TemplateException`s was suppressed in certain situations resulting in half-rendered pages without error message.

- Bugfix: FreeMarker didn't work if the `javax.servlet` classes was not available, because `Configuration` explicitly referred to `javax.servlet.ServletContext`.

- Bugfix: classes may were not found if they was available only in the `WEB-INF`, and FreeMarker tried to load the class dynamically.

- Bugfix: the `Template` constructor (and thus `Configuration.getTemplate`) sometimes threw `TokenMgrError` (a non-checked exception) instead of `ParseException`.

##### Other changes

- The Web application related examples has been replaced.

##### The history of the releases before the final version

###### Differences between the final and RC2 releases

- You can load settings from `.properties` file with the `setSettings` method of `Configuration` and other `Configurable` subclasses.

- New string built-in: `uncap_first`

- Bugfix: When exposing an XML document to a template and accessing it with XPath using Jaxen a `ClassCastException` has occurred.

- Bugfix: The template cache has loaded templates with bad `Configuration` instance in certain situations if you use not the static default `Configuration` instance.

###### Differences between the RC2 and RC1 releases

- Non backward compatible change!: `FreemarkerServlet` now uses the encoding of the template file for the output, unless you specify the encoding in the `ContentType` init-param, such as `text/html; charset=UTF-8`.

- Non backward compatible change compared to RC1!: The `capture_output` transform creates variable in the current namespace (as `assign` directive) with the `var` parameter, not a global variable.

- The new and preferred way of number formatting with `string` built-in is `foo?string(format)`, instead of the less natural `foo?string[format]`.

- The `string` built-in works for boolean values. For example: `${spamFilter?string("enabled", "disabled")}`. For more information read the reference.

- The default strings for outputting boolean value using the `string` built-in can be set using the `boolean_format` setting.

- String literals can be quoted with apostrophe-quote. `"foo"` and `'foo'` are equivalent.

- The new interface `freemarker.cache.CacheStorage` allows users to plug custom template caching strategies with the `cache_storage` setting. The core package now ships with two implementations: `SoftCacheStorage` and `StrongCacheStorage`. For more information read:

- You can set settings with string name and string value with the new `setSetting(String key, String value)` method of `Configurable` super-classes (as `Configuration`).

- Other new `Configuration` methods: `getTemplateLoader`, `clone`.

- `assign`, `local` and `global` now can capture the output generated be the nested template fragment into the variable. This deprecates `capture_output` transform. More information: assign directive reference

- Other new `Configuration` methods: `getTemplateLoader`, `clone`.

- Changes to `TemplateTransformModel` interface: `getWriter` can throw `IOException`, and can return `null` if the transform does not support body content.

- Till now `TemplateTransformModel.getWriter` has received null as parameter map if the transform was called without parameters. From now, it will receive an empty Map instead. Note that the previous API documentation didn't state that it always receives null if there are no parameters, so hopelessly only very few classes exploit this design mistake.

- Changes to `TemplateControl` interface: `onStart` and `afterBody` methods are now allowed to throw `IOException`.

- Path that contains `//:` is considered as absolute path.

- New string built-ins: `index_of`, `last_index_of`, `starts_with`, `ends_with`, `replace`, `split`, `chop_linebreak`.

- New sequence built-ins: `sort`, `sort_by`.

- All `Configuration` level settings can by set with Servlet init-params (`template_exception_handler`, `locale`, `number_format`, etc.).

- Bugfix: classes may were not found if they was available only in the `WEB-INF`, and FreeMarker tried to load the class dynamically.

- Bugfix: `setLocalizedLookup(false)` of `Configuration` was overridden when you have called `setTemplateLoader`.

- Bugfix: String concatenation had performance problem if there was multiple concatenations chained, as: `"a"+x+"a"+x+"a"+x+"a"+x+"a"+x`.

- Bugfix: white-space stripping was not worked with tags spanning over multiple lines.

- Bugfix: Removing several dependencies on JDK 1.3, so FreeMarker can be build for JDK 1.2.2.

###### Differences between the Preview 2 and RC1 releases

- `ftl` is now stricter, and does not allow custom parameters. To associate custom attributes to templates, we may add a new directive later, if there is a demand for it.

- `escape` directive does not affect numerical interpolations (`#{...}`) anymore, as it has caused errors with string escapes as `?html`.

- The `normalizeName` method of `freemarker.cache.TemplateLoader` has been removed, because it has caused too many complications. Instead, normalization happens on a single point in the `TempateCache`. In consequence, FreeMarker is now stricter about the format of template paths, as things like `/../` are interpreted by the core.

- Experimental feature: With the `setSimpleMapWrapper` method of `BeansWrapper` you can configure it to wrap `java.util.Map`-s as `TemplateHashModelEx`-s, and do not expose the methods of the object.

- New `Configuration` methods: `set/getLocalizedLookup`, `clearTemplateCache`, `clearSharedVariables`.

- More cleanups in the `Environment` API.

- Better JSP standard compliance: JSP page-scope variables are the global variables that were created in the template (not the variables of the data-model).

- JDOM independent XML-wrapping: `freemarker.ext.xml.NodeListModel` is a re-implementation of `freemarker.ext.jdom.NodeListModel` that does not rely on JDOM; you don't need JDOM .jar anymore. The new `NodeListModel` automatically uses W3C DOM, dom4j, or JDOM, depending on which library is available (that is, depending on what object do you pass to its constructor).

- Bugfix: `WebappTemplateLoader`: Template updating didn't worked correctly with Tomcat due the caching of resources. Now `WebappTemplateLoader` tries to access the resources directly as `File`, if it is possible, thus bypasses the caching.

- Bugfix: Templates loaded with `MultiTemplateLoader` subclasses was removed from the template cache after the template update delay has elapsed (5 seconds by default) even if the template file was unchanged. This can cause lot of extra load for a high-traffic server if you have many templates or if the template update delay was set to 0 second.

- Bugfix: Undefined variables in hash and sequence constructors (as `[a, b, c]`) didn't caused errors.

###### Differences between the Preview 1 and Preview 2 releases

- All 16-bit Unicode letters and numbers are allowed in identifiers, as well as the `$` character (as in Java programming language). Thus you can use accented letters, Arabic letters, Chinese letters, etc. as identifiers in templates

- Macros now can create loop variables for the nested content. For more information read this.

- New directives: `t`, `rt` and `lt` directives allow you to do explicit white-space removal in extreme FTL applications. For more information read the reference.

- The syntax of assignment-with-namespace has changed from `<#assign foo=123 namespace=myLib>`) to `<#assign foo=123 in myLib>`, since the previous syntax was confusing because its similarity to a bulk-assignment.

- Bulk assignments (as `<#assign x=1, y=2, z=3>`) no longer need colon to separate the assignments (as `<#assign x=1 y=2 z=3>`), although it is still allowed to preserve backward compatibility.

- Positional parameter passing is supported for macro calls as shorthand form of normal named parameter passing. For more details read read the reference.

- New built-in, `namespace`, to get the namespace of the currently executing macro.

- `TransformControl` interface (was experimental earlier): If the `Writer` returned by `TemplateTransformModel.getWriter` implements this interface, it can instruct the engine to skip or to repeat evaluation of the nested content, and gets notified about exceptions that are thrown during the nested content evaluation. For more information please read the API documentation.

- Jython wrapper can now wrap arbitrary Java objects, not only `PyObject`-s. If an object is passed to the wrapper that is neither a `TemplateModel`, nor a `PyObject`, it is first coerced into a `PyObject` using Jython's own wrapping machinery, and then wrapped into a `TemplateModel` as any other `PyObject`.

- Some cleanups in the `Environment` API.

- The Web application related examples has been replaced.

- Bugfix: Templates loaded with `URLTemplateLoader` subclasses was removed from the template cache after the template update delay has elapsed (5 seconds by default) even if the template file was unchanged. This can cause lot of extra load for a high-traffic server if you have many templates or if the template update delay was set to 0 second.

- Bugfix: `FreeMarkerServlet` has thrown `ServletException` even if a debug `TemplateException` handler was in use (so you may got Error 500 page instead of debug information).

#### 2.1.5

Date of release: 2003-02-08

##### Changes on the Java side

- Bugfix: Fixed a bug that forced the cache to frequently reload templates accessed through URL and multi template loaders: Templates loaded with `URLTemplateLoader` subclasses and `MultiTemplateLoader` was removed from the template cache after the template update delay has elapsed (5 seconds by default) even if the template file was unchanged. This can cause lot of extra load for a high-traffic server if you have many templates or if the template update delay was set to 0 second.)

- Bugfix: Many anomalies in the `JythonWrapper` were resolved, making the integration with Jython much smoother: Jython wrapper can now wrap arbitrary Java objects, not only `PyObject`-s. If an object is passed to the wrapper that is neither a `TemplateModel`, nor a `PyObject`, it is first coerced into a `PyObject` using Jython's own wrapping machinery, and then wrapped into a `TemplateModel` as any other `PyObject`.

#### 2.1.4

Date of release: 2002-12-26

##### Changes on the Java side

- Bugfix: Log4J is now found when automatically discovering the logging library to use.

- Bugfix: An exception is no longer thrown in the static initializer of the `Configuration` if the directory specified in the `"user.dir"` system property is not readable.

#### 2.1.3

Date of release: 2002-12-09

##### Changes on the FTL side

- Bugfix: `cap_first` built-in did what `double` built-in does.

##### Other changes

- The official extension of FreeMarker template files is `ftl` from now, not `fm`. (This is the name of the template language; FTL, for FreeMarker Template Language.) Of course you can use any extensions, since FreeMarker does not deal with the file extension. But we recommend `ftl` extension as default.

- Web application examples got tweaked again, as under JDK 1.4 a class in an explicit (named) package can no longer import classes from the default (unnamed) package. Our webapp example was using classes in the default package, they are now moved into named packages.

#### 2.1.2

Date of release: 2002-11-28

##### Changes in FTL (FreeMarker Template Language)

- `FreeMarkerServlet` now has a setting for the `Content-Type` header of the response, defaulting to `text/html`. Previously it set no content type, which made it not play nicely when integrated with software that expected it (i.e. OpenSymphony SiteMesh).

- `FreeMarkerServlet` now works correctly when mapped to an URL extension instead of URL path prefix.

- You can emulate `include` directive call within Java code by calling `Environment.include(templateName, charset, parse)`.

- Bugfix: When `Template.process()` was called from another template processing, it set `currentEnvironment` to null when it returned, thus crashed the parent template processing.

- Bugfix: the `_descendant` key in JDOM support incorrectly left the document root element out of the result when applied to a Document node.

- Bugfix: because we incorrectly assumed certain behavior of JDK 1.4 Beans introspector, calls to public interface methods on non-public classes that implement the interface were causing exceptions on JDK 1.4

##### Other changes

- Various minor supplements to the manual.

- Documentation HTML pages don't try to load the SourceForge logo from the Internet anymore.

- The default ant target is `jar`, not `dist`.

#### 2.1.1

Date of release: 2002-11-04

##### Changes in FTL (FreeMarker Template Language)

- Multi-type variables that are both string and number or string and date are now output using their number or date value instead of the string value when used in the `${...}` interpolation. This practically makes the string part of a string/number or a string/date variables useless.

- Bugfix: operator ``or'' (`||`) worked wrongly when its left operand was a composite expression (e.g. the second `||` in `false || true || false`; this was evaluated to `false`, but it should be `true`)

- Bugfix: Less-than sign inside comments confused the FTL parser (e.g. `<#-- blah < blah -->`); it commented out everything after the problematic comment.

- Bugfix: Comparing two numerical constants (e.g. `3 == 3`) caused internal error in the FTL parser, and aborted template processing with error.

- Experimental date/time type support was removed, since it seems that this initial implementation was misguided. FreeMarker 2.2 will certainly support data/time.

##### Changes on the Java side

- Bugfix: `Number`s wrapped with `BEANS_WRAPPER` was displayed with the `toString()` method of wrapped object. Now they are rendered according to the `number_format` setting, because multi-type variables that are both string and number are now output using their number value instead of the string value.

- Experimental date/time type support was removed, since it seems that this initial implementation was misguided. FreeMarker 2.2 will certainly support data/time.

#### 2.1

Date of release: 2002-10-17

Templates and the Java API are not fully compatible with 2.0 releases. You will need to revisit existing code and templates, or use 2.1 for new projects only. Sorry for this inconvenience; FreeMarker has undergone some revolutionary changes since the 1.x series. We hope things will soon be sufficiently mature for us to offer (almost) backward-compatible releases. Note that there is a backward-compatibility flag that can be set via `Configuration.setClassicCompatible(true)` that causes the new FreeMarker to emulate most of FreeMarker 1.x's quirks.

##### Changes in FTL (FreeMarker Template Language)

- More strict, reveals accidental mistakes in the templates, prevents showing incorrect information when something went wrong:

  - An attempt to access an undefined variable causes an error and aborts template processing (by default at least; see later). In earlier versions undefined variables were silently treated as empty (zero-length) strings. However, you can handle undefined variables in the template with some new built-ins. For example, `${foo?if_exists}` is equivalent with the `${foo}` of earlier versions. Another way of looking at this is that null values no longer exist from the viewpoint of a template designer. Anything referenced must be a defined variable.

    Note however that the programmer can configure FreeMarker so that it ignores certain errors (say, undefined variables), and continues template processing by skipping the problematic part. This ``loose'' policy should be used only for sites that don't show critical information.

  - New variable type: boolean. Conditions in `if`/`elseif` and operands of logical operators (`&&`, `||`, `!`) must be booleans. Empty strings are no longer treated as a logical false.

- Local and global variables. More info:

  - Local variables for macros. You can create/replace local variables in macro definition bodies with the `local` directive

  - You can create/replace global (non-local) variables with the `global` directive

- The `include` directive now by default treats the passed filename as being relative to the including template's path. To specify absolute template paths, you now have to prepend them with a slash.

- The `include` directive can now use the acquisition algorithm (familiar from the Zope system) to look up the template to include. Basically, if a template is not found where it is looked up first, it is looked up in parent directories. This is however not a default behavior, rather it is triggered by a new syntactic element.

- Strict syntax mode: Allows you to generate arbitrary SGML (XML) without worrying about clashes with FreeMarker directives. For more information read:

- Terse comments: you can use `<#-- ... -->` instead of `<comment>...</comment>`

- Directive that you can use to change the locale (and other settings) inside the template: `setting`

- Directive to explicitly flush the output buffer: `flush`

- The top-level (root) hash is available via the variable `root`, which is now a reserved name.

- The misnamed `function` directive has been renamed to `macro`.

- String literals support various new escape sequences, including UNICODE escapes (`\xCODE`)

- The `compress` directive is now more conservative in removing line breaks.

- Built-in to capitalize the first word: `cap_first`

- Built-in to generate on-the-fly templates: `interpret`

- `stop` directive has an optional parameter to describe the reason of termination

- Better error messages.

- New variable type: date. Date support is experimental. It can change substantially in the future. Keep this in mind if you use it.

##### Changes on the Java side

- `ObjectWrapper`: You can put non-`TemplateModel` objects directly into hashes, sequences and collections, and they will be automatically wrapped with the appropriate `TemplateModel` implementation. The API of objects that are exposed to templates (`SimpleXXX`) has been changed according to this, for example in `SimpleHash` the old `put(String key, TemplateModel value)` is now `put(String key, Object object)`. Also, you can pass any kind of object as data-model to `Template.process`. The alternative reflection based `ObjectWrapper` can expose the members of any Java object automatically for the designer. More information: Object wrapping, Bean wrapper, Jython wrapper.

- The `Configuration` object was introduced as a central point to hold all your FreeMarker-related global settings, as well as commonly used variables that you want to have available from any template. Also it encapsulates the template cache and can be used to load templates. For more information read .

- `TemplateLoader`: pluggable template loader, separates caching from template loading

- `TemplateNumberModel`-s do not control their formatting anymore. They just store the data (i.e. a number). Number formatting is done by the FreeMarker core based on the `locale` and `number_format` settings. This logic applies to the new experimental date type as well.

- `TemplateBooleanModel` introduced: Only objects that implements this interface can be used as a boolean in true/false conditions. More info:

- `TemplateDateModel` introduced: objects that implements this interface are recognized as dates and can be locale-sensitively formatted. Date support is experimental in FreeMarker 2.1. It can change substantially in the future. Keep this in mind if you use it.

- The `TemplateModelRoot` interface was deprecated. As of FreeMarker 2.1, you can simply use any instance of `TemplateHashModel` instead. This actually is due to a significant architectural change. Variables set or defined in a template are stored in a separate `Environment` object that only exists while the template is being rendered. Thus, the template doesn't modify the root hash.

- Changes to transformations

  - Completely rewritten `TemplateTransformModel` interface. More flexible, and does not impose output holding. More information:

  - The `transform` directive now takes an optional set of key/value pairs. `<transform myTransform; key1=value1, key2=value2 ...>`. More information: `transform` directive

  - The transforms that ship with the FreeMarker core are now available by default to all templates - i.e. `<transform html_escape>` will invoke the `freemarker.template.utility.HtmlEscape` transform. More information:

- User-defined `TemplateModel` objects now can access the runtime environment (read and set variables, get the current locale, etc.) using an `Environment` instance, which can be obtained by the static `Environment.getCurrentEnvironment()` method. As a result, `TemplateScalarModel.getAsString` has been changed: it has no locale parameter.

- `TemplateExceptionHandler`-s make it possible to define your own rules on what to do when a runtime error occurs (e.g. accessing a non existing variable) during template processing. For example, you can abort template processing (recommended for most sites), or skip the problematic statement and continue template processing (similar to old behavior). DebugMode has been removed, use `TemplateExceptionHandler.DEBUG_HANDLER` or `HTML_DEBUG_HANDLER` instead.

- Logging: FreeMarker logs certain events (runtime errors for example). For more information read .

- `SimpleIterator` was removed, but we provide a `TemplateCollectionModel` implementation: `SimpleCollection`.

- Arithmetic engine is pluggable (`Configuration.setArithmeticEngine`). The core distribution comes with two engines: `ArithmeticEngine.BIGDECIMAL_ENGINE` (the default) that converts all numbers to `BigDecimal` and then operates on them, and `ArithmeticEngine.CONSERVATIVE_ENGINE` that uses (more-or-less) the widening conversions of Java language, instead of converting everything to `BigDecimal`.

- Changes to `freemarker.ext.beans` package: The JavaBeans adapter layer has suffered several major changes. First, `BeansWrapper` is no longer a static utility class - you can now create instances of it, and every instance can have its own instance caching policy and security settings. These security settings are also new - you can now create JavaBeans wrappers that hide methods that are considered unsafe or inappropriate in a templating environment. By default, you can no longer call methods like `System.exit()` from the template (although you can manually turn off these safeguards). The `StaticModel` and `StaticModels` classes are gone; their functionality is now replaced with the `BeansWrapper.getStaticModels()` method.

- `freemarker.ext.jython` package: FreeMarker can now directly use Jython objects as data-models using the Jython wrapper.

- Changes to `freemarker.ext.jdom` package: The package now uses the Jaxen package instead of its predecessor, the werken.xpath package to evaluate XPath expressions. Since Jaxen is a successor to werken.xpath, this can be considered to be an upgrade. As a consequence, namespace prefixes are now recognized in XPath expressions and the overall XPath conformance is better.

- Better error reporting: If the processing of a template is aborted by a `TemplateException` being thrown, or using a `<#stop>` directive, FreeMarker will now output an execution trace with line and column numbers relative to the template source.

- The output is written to a simple `Writer`; no more `PrintWriter`. This redesign causes FreeMarker to no longer swallow `IOException`s during template processing.

- Various API cleanups, primarily the removing of superfluous constructor and method overloads.

##### Other changes

- Documentation has been rewritten from scratch

##### Differences between the RC1 and final release

- Added the support for date models and locale-sensitive date formatting. Date support is experimental in FreeMarker 2.1. It can change substantially in the future. Keep this in mind if you use it.

- Added the `default` built-in which makes it possible to specify default values for undefined expressions.

- `SimpleIterator` has been removed, `SimpleCollection` has been introduced

- Arithmetic engine is pluggable. The core now contains two arithmetic engines: `ArithmeticEngine.BIGDECIMAL_ENGINE` and `ArithmeticEngine.CONSERVATIVE_ENGINE`.

- `BeansWrapper` supports a new exposure level: `EXPOSE_NOTHING`

- `Constants` interface was removed. `..._WRAPPER` constants have been moved from `Constants` to `ObjectWrapper`, `EMPTY_STRING` constant was moved to `TemplateScalarModel`, `NOTHING` constant was moved to `TemplateModel`, `TRUE` and `FALSE` constants were moved to `TemplateBooleanModel`.

- `JAVABEANS_WRAPPER` was renamed to `BEANS_WRAPPER`

- `Configuration.get` and `put`, `putAll` were renamed to `getSharedVariable` and `setSharedVariable`, `setAllSharedVariables`

- `Configuration.getClassicCompatibility`, `setClassicCompatibility` were renamed to `isClassicCompatible`, `setClassicCompatible`

- `Template.process` method overloads with `useReflection` parameter was removed. But now we have `setObjectWrapper` method in the `Configuration`, so you can set the preferred root-object wrapper there.

- Some superfluous method overloads were removed; these changes are backward compatible with RC1

- Various minor JavaDoc and Manual improvements

- Bugfix: `include` directive has calculated the base path of relative paths wrongly

- Bugfix: We have accidentally used a J2SE 1.3 class, but FreeMarker 2.1 must able to run on J2SE 1.2

#### 2.01

The main improvement is in error reporting. Now exceptions are much more informative since they come with complete line number and column information.

The only API change between 2.0 and 2.01 was the elimination of the CacheListener/CacheEvent API. Now, if the updating of a template file fails, the exception is thrown back to the caller to handle. If you want logging to occur when a template file is updated successfully, you can override the logFileUpdate() method in FileTemplateCache.

#### 2.0

FreeMarker 2.0 final was released on 18 April 2002. The changes with respect to the previous release, 2.0 RC3 are fairly minor.

##### Bugfixes

- There were a couple of bugs in handling null values, where Lazarus did not do the same thing as FreeMarker Classic. Traditionally, in FreeMarker, nulls were treated as being equivalent to an empty string in the appropriate context. At this point, to the best of our knowledge, there is backward compatibility with FreeMarker Classic in this respect.

- Literal strings can now include line breaks. This was a backward compatibility issue with FreeMarker Classic that has been fixed.

##### Changes to the Template language

- You can use the extra built-in of `myString?web_safe` to convert a string to its "web-safe" equivalent, where problematic characters such as '<' are converted to &lt;.

- In displaying numbers with a fractional part, the rendering apparatus now respects the decimal separator of the template's locale, so that, for example, in continental Europe, you would see 1,1 and in the U.S. locale, 1.1.

##### Changes to the API

- The `getAsString()` method in the `TemplateScalarModel` interface now takes a `java.util.Locale` as a parameter. For the most part, this is a hook for later use. In the default implementation, `SimpleScalar`, this parameter is unused. If you are implementing this interface yourself, your implementation may ignore the parameter. However, it will be appealing for certain implementations.

- The constructors of `FileTemplateCache` have changed. If you are using an absolute directory on the file system as the location of your templates, you need to pass in an instance of `java.io.File` to indicate the location. If you use the constructors that take a string, this is taken to mean relative to the classloader classpath.

##### Miscellany

The ant build script build.xml now contains a target that builds a .war file containing the Hello, World and Guestbook examples. It builds a fmexamples.war. For example, if you are using Tomcat in its out-of-the-box configuration, you would place this under <TOMCAT_HOME>/webapps and then you would use http://localhost:8080/fmexamples/servlet/hello and http://localhost:8080/fmexamples/servlet/guestbook for the Hello, World and Guestbook examples respectively.

#### 2.0 RC3

FreeMarker 2.0 RC3 was released on 11 April 2002. This release was primarily devoted to fixing bugs that were reported in RC2.

##### Bug Fixes

- Variables defined in an <include...> were not available in the enclosing page. This has been fixed.

- The JavaCC parser was not configured to handle Unicode input correctly. Now, Unicode support is working.

- There was a bug when comparing a number with null. It should have returned false, but threw an exception instead. This has been fixed.

##### Changes to the Template Language

- The syntax of the include directive has changed. To indicate an unparsed include file, you do as follows:

      <include "included.html" ; parsed="n" >

  You can also indicate the encoding of the included file this way:

       <include "included.html" ; encoding="ISO-8859-5">

- The built-in myString?trim was added for trimming the leading and trailing white-space from strings.

##### API changes

- The TemplateEventAdapter machinery was taken out. This was never set up in a very useful manner and we anticipate that version 2.1 will have more complete support for logging events.

- The template caching mechanism was streamlined and simplified.

- The FileTemplateCache can now be configured to load files relative to a class loader, using the Class.getResource() call. This allows templates to be bundled up in .jar files or in a .war file for easy deployment of web-based apps.

#### 2.0 RC2

FreeMarker 2.0 RC 2 was released on 4 April 2002. Here is a summary of changes wrt to the first release.

##### Changes to Template Language

- Certain built-in functionality is provided via a new operator, '?'. Thus, `myList?size` provides the number of elements in a list. Similarly, `myString?length` provides the length of a string, `myString?upper_case` puts the string all in capital letters, and `myHash?keys` provides a sequence containing the keys in the hash. See for list of all available built-ins.

- Numerical comparisons can now be made using the "natural" operators < and > but there are also "web-safe" alternatives, such as \lt and \gt, since the use of these characters may confuse HTML editors and parsers. Note that these changed between rc1 and rc2, they now start with a backslash. A little asymmetry is the fact that if you use the natural greater-than or greater-than-or-equals operators (i.e. > or >=) the expression must be in parentheses. With any other operator, the parentheses are optional.

- Within an iteration loop -- i.e. a `foreach` or a `list` block -- the current count in the loop is available as the special variable `index_count`. where index is the name of the variable in the iteration. A boolean variable called `index_has_next` is also defined that indicates whether there are any more items in the iteration after this one. Note that the index starts at zero, so you will often be adding one to it in practice.

- The `<#break>` directive can now be used to break out of a `<#foreach...>` or a `<list...>` loop. (Prior to this version, it only worked within a switch-case block.) There is a new directive called `<#stop>` that, when encountered, simply halts processing of the template. This can be useful for debugging purposes.

- When invoking java methods that have been exposed to the page, using the code in freemarker.ext.*, there are built-ins that allow you to indicate the numerical type that you wish to pass as the value. For instance, if you had two methods, one that takes an int and another that takes a long, and you wanted to pass in a value, you would have to specify which method. `myMethod(1?int)` or `myMethod(1?long)`. This is unnecessary if there is only one method of the given name.

- Ranges can be used to get the sublist from a list or the substring of a string. For example: `myList[0..3]` will return items 0 through 3 of the list in question. Or, for example, you could get all the elements of the list except for the first and last ones via: `myList[1..(myList?size-2)]`

- Or we could get the first 6 characters of a string via `myString[0..5]`

- Lists can be concatenated using the '+' operator. Previously, this overloading of '+' only applied to strings.

- An attempt to compare a number to a string now throws an exception, since it is indicative of a coding error. Note that there is a backward compatibility mode that can be set (see below) that loosens this up in order to be able to process legacy templates.

##### API Changes

- The `TemplateSequenceModel` interface now has a `size()` method for getting the number of elements in the sequence in question.

- The `TemplateModelIterator` interface now has a `hasNext()` method.

- The default sequence and hash implementations, `freemarker.template.SimpleSequence` and `freemarker.template.SimpleHash` are now unsynchronized. If you need the methods to be synchronized, you can get a synchronized wrapper via the `synchronizedWrapper()` in either class.

- The `freemarker.utility.ExtendedList` and `freemarker.utility.ExtendedHash` classes were removed, since all of the extra keys that it defined are now available using the appropriate '?' built-in operation, i.e. `myHash?keys` or `myList?size` or `myList?last`.

- There is a method in `java.freemarker.Configuration` named `setDebugMode()` which allows you to decide whether stack traces are simply output to the web client (the best situation in development) or thrown back to the caller to be handled more gracefully (the best situation in production).

- There is a flag that can be set to turn on a processing mode that is more backward-compatible with FreeMarker Classic. This is off by default, but you can set it via `Template.setClassicCompatibility(true)`. What this does is that it allows scalars to be treated as a single-item list in a list directive. Also, it allows somewhat more looseness about types. In FreeMarker 1.x, `<#if x=="1">` and `<#if x==1>` were in fact equivalent. This meant that legacy templates might tend to be slack about this. If classic compatibility is not set, an attempt to compare the string "1" with the number 1 will result in an exception being thrown. (Note that it is preferable to get your templates working without the backward compatibility flag, since it usually will require only minor changes. However, for people with a lot of templates and no time to check over them, this flag may be of use.)

#### 2.0 RC1

The first public release of FreeMarker 2.0 was on 18 March 2002. Here is a summary of the changes in the Lazarus release, with respect to the last stable release of FreeMarker Classic.

NOTA BENE:

Despite the changes delineated above, the Lazarus release is almost entirely backward-compatible with FreeMarker Classic. We believe that most existing code and templates that work under FreeMarker Classic will continue working under Lazarus, with at most minimal changes. In practice, the most common cases where legacy template code is broken will be where assumptions were made about numbers and strings being equivalent. Note that in FreeMarker 2, 2 + 2 does not result in "22". The String "1" and the number 1 are entirely different animals and thus, any code will be broken if it relies on the boolean expression ("1"==1) being true. There is a "classic compatibility mode" that can be set via: `Template.setClassCompatibility()` that can be set so that Lazarus emulates some of the quirky behavior of FreeMarker Classic. However, any code that relied on the above "features" of FreeMarker classic really should be reworked. You are less likely to run into the other incompatibilities that are listed above. If you come across any other anomalies, please do tell us about them.

##### Support for Numerical operations, both arithmetic and boolean, as well as numerical ranges.

- Scalars can now be either strings or numbers. (In FreeMarker Classic all scalars were strings.) The basic operations allowed are addition, subtraction, multiplication, division, and modulus using the `+`, `-`, `*`, `/`, and `%` operators respectively. Arbitrary-precision arithmetic with integers and floating point numbers are provided. Though our goal is definitely to follow the principle of least surprise, for backward compatibility, the `+` operator still is used for string concatenation. If either the left hand side or the right hand side of `lhs + rhs` is non-numerical, we revert to interpreting this as string concatenation. Thus, in FreeMarker 2, 2+2 evaluates to the number 4, while any of "2"+2 or 2+"2" or "2"+"2" evaluate to the string "22". In FreeMarker Classic, rather embarrassingly, all of the above, including 2+2, evaluated to the string "22". An attempt to use any other arithmetic operator besides the `+` with non-numerical operands will cause an exception to be thrown.

- Output of a numerical expression can be made explicit via the alternative `#{....}` syntax. If the expression within the curly parentheses does not evaluate to a numerical value, an exception is thrown. The older ${....} syntax can evaluate to either a number or a string. In general, if, for logical reasons, the output must be numerical, it is preferable to use the #{...} syntax, since it adds an extra sanity check. Note that if, by some miracle, the character sequence "#{" occurs in your template, you will have to use a workaround to prevent problems. (The <noparse> directive is one possibility.)

- In this release, there is a facility for specifying the number of digits to show after the decimal point. The following code specifies to show at least 3 digits after the decimal point but not more than 6. This is optional. This option is only available if you use the #{...} syntax.

      #{foo + bar ; m3M6}

  (Note that the above is something of a stopgap measure. Future releases will move toward supporting fully internationalization and localization of number and currency formatting.

- Numerical expressions can be used in boolean expressions via the comparison operators: `lt`, `gt`, `lte`, and `gte`. In the web space, where FreeMarker is most used in practice, using the more natural operators such as < and > would tend to confuse HTML-oriented editors. An attempt to compare non-numerical expressions using these operators leads to a `TemplateException` being thrown. If, by some coincidence, you have variables named "lt", "gt", "lte", or "gte", you will have to change their names, since they are now keywords in the language.

- Numerical ranges are supported.

      <#list 1990..2001 as year>
        blah blah in the year ${year} blah
      </#list>

  The left hand and right hand sides of the `..` operator must be numerical, or an exception is thrown. They also need not be literal numbers, but can be more complex expressions that evaluate to a numerical scalar value. Note that it is also possible to write a range that descends in value:

      <#list 2001..1990 as year>
        blah blah in the year ${year} blah blah
      </#list>

##### API Changes

- The `TemplateNumberModel` interface and the `SimpleNumber` implementation were added to support exposing numerical values.

- The `TemplateListModel` API in FreeMarker Classic had some design problems -- particularly in terms of supporting thread-safe code. It has been deprecated in favor of the following API's: `TemplateCollectionModel` and `TemplateSequenceModel`. The `SimpleList` class was refactored to implement the above interfaces (and paradoxically, does not implement the TemplateListModel interface.) Code that uses the deprecated `TemplateListModel` should be refactored.

- The Expose Package by Attila Szegedi has been made an integral part of the FreeMarker distribution and is now under the freemarker.ext.* hierarchy. This package provides advanced models for representing arbitrary Java objects as template models, for representing XML documents as template models, as well as classes to facilitate the integration of FreeMarker with servlets and Ant.

- In FreeMarker Classic, there were some utility classes such as `freemarker.template.utility.Addition` etcetera that existed as workarounds for the lack of numerical operations in FreeMarker. Those have been removed and will probably not be missed.

- In FreeMarker Classic, the `SimpleScalar` object was mutable, it had a `setValue` method. This was fairly obviously a design mistake. Any code that relied on this must be refactored. Note that in this release, both `SimpleScalar` and the newly introduced `SimpleNumber` are both immutable and final.

##### Syntactical Miscellany

- The if-elseif-else syntax was introduced. FreeMarker classic only had if-else. This construct should probably (in the opinion of the author of this document -- Revusky) be used in preference to switch-case since the switch-case with fall-through is a notoriously error-prone construct for most mortal men.

- You can now do a multiple assignment in one <assign...> directive. For example: `<assign x = 1, y = price*items, message="foo">`

- A scalar will no longer be interpreted as a one-item list in a <list...> or <#foreach...> block. If you have code that relied on this feature, there is an easy workaround, since you can simply define a list literal with exactly one item.

       <assign y=[x]>
       and then...
       <list y as item>...</list>

### License

    FreeMarker 1.x was released under the LGPL license. Later, by community
    consensus, we have switched over to a BSD-style license. As of FreeMarker
    2.2pre1, the original author, Benjamin Geer, has relinquished the copyright in
    behalf of Visigoth Software Society. The current copyright holder is the
    Visigoth Software Society.

    ------------------------------------------------------------------------------
    Copyright (c) 2003 The Visigoth Software Society. All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1.  Redistributions of source code must retain the above copyright notice,
        this list of conditions and the following disclaimer.

    2.  The end-user documentation included with the redistribution, if any, must
        include the following acknowlegement:
          "This product includes software developed by the
          Visigoth Software Society (http://www.visigoths.org/)."
        Alternately, this acknowlegement may appear in the software itself, if and
        wherever such third-party acknowlegements normally appear.

    3.  Neither the name "FreeMarker", "Visigoth", nor any of the names of the
        project contributors may be used to endorse or promote products derived
        from this software without prior written permission. For written
        permission, please contact visigoths@visigoths.org.

    4.  Products derived from this software may not be called "FreeMarker" or
        "Visigoth" nor may "FreeMarker" or "Visigoth" appear in their names
        without prior written permission of the Visigoth Software Society.

    THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
    FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
    VISIGOTH SOFTWARE SOCIETY OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
    INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
    BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
    DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
    OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
    EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    ------------------------------------------------------------------------------

    This software consists of voluntary contributions made by many individuals on
    behalf of the Visigoth Software Society. For more information on the Visigoth
    Software Society, please see http://www.visigoths.org/

    ------------------------------------------------------------------------------

    FREEMARKER SUBCOMPONENTS UNDER DIFFERENT LICENSE:

    FreeMarker includes a number of subcomponents that are licensed by the Apache
    Software Foundation under the Apache License, Version 2.0. Your use of these
    subcomponents is subject to the terms and conditions of the Apache License,
    Version 2.0. You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    The subcomponents under this licence are the following files, which are
    included both in freemarker.jar and in the source code:

        freemarker/ext/jsp/web-app_2_2.dtd
        freemarker/ext/jsp/web-app_2_3.dtd
        freemarker/ext/jsp/web-app_2_4.xsd
        freemarker/ext/jsp/web-app_2_5.xsd
        freemarker/ext/jsp/web-jsptaglibrary_1_1.dtd
        freemarker/ext/jsp/web-jsptaglibrary_1_2.dtd
        freemarker/ext/jsp/web-jsptaglibrary_2_0.xsd
        freemarker/ext/jsp/web-jsptaglibrary_2_1.xsd

license
Start-tag

  Tag, which indicates that the following content is under the element, up to the end-tag. The start-tag may also specifies attributes for the element. An example of a start-tag: `<body bgcolor=black>`

Boolean

  This is a variable type. A boolean variable represents a logical true or false (yes or no). For example, if the visitor has been logged in or not. There are only two possible boolean values: `true` and `false`. Typically, you will use booleans with an `<#if ...>` directive when you want to display text based on some condition, say, you show a certain part of the page only for visitors who has logged in.

Character

  A symbol that people use in writing. Examples of characters: Latin capital letter A (``A''), Latin small letter A (``a''), digit four (``4''), number sign (``#''), colon (``:'')

Charset

  A charset is a rule (algorithm) for transforming a sequence of characters (text) to a sequence of bits (or in practice, to a sequence of bytes). Whenever a character sequence is stored on a digital media, or sent through a digital channel (network), a charset must be applied. Examples of charsets are ISO-8859-1, ISO-8859-6, Shift_JIS , UTF-8.

  The capabilities of different charsers are different, that is, not all charsets can be used for all languages. For example ISO-8859-1 can't represent Arabic letters, but ISO-8859-6 can, however it can't represent the accented letters that that ISO-8859-1 can. Most charsets are highly restrictive regarding the allowed characters. UTF-8 allows virtually all possible characters, but most text editors can't handle it yet (2004).

  When different software components exchange text (as the HTTP server and the browser, or the text editor you use for saving templates and FreeMarker who loads them), it's very important that they agree in the charset used for the binary encoding of the text. If they don't, then the binary data will be misinterpreted by the receiver (loader) component, which usually results in the distortion of the non-English letters.

Output encoding

  Means output charset. In the Java world the term ``encoding'' is commonly (mis)used as a synonym to ``charset''.

Template encoding

  Means template charset. In the Java world the term ``encoding'' is commonly (mis)used as a synonym to ``charset''.

Collection

  A variable that (in conjunction with the `list` directive) can spit out a series of variables.

Data-model

  Something that holds the information the template has to show (or use in some other ways) when the template processor assembles the output (e.g. a Web page). In FreeMarker this is best visualized as a tree.

Directive

  Instructions to FreeMarker used in FTL templates. They are invoked by FTL tags.

Element

  Elements are the most fundamental building pieces of SGML documents; an SGML document is basically a tree of elements. Example of elements used in HTML: body, head, title, p, h1, h2.

End-tag

  Tag, which indicates that the following content is not under the element. Example: `</body>`.

Environment

  An `Environment` object stores the runtime state of a single template template processing job. That is, for each `Template.process(...)` call, an `Environment` instance will be created, and then discarded when `process` returns. This object stores the set of temporary variables created by the template, the value of settings set by the template, the reference to the data-model root, etc. Everything that is needed to fulfill the template processing job.

Extensible Markup Language

  A subset (restricted version) of SGML. This is less powerful than SGML, but it easier to learn and much easier to process with programs. If you are an HTML author: XML documents are similar to HTML documents, but the XML standard doesn't specify the usable elements. XML is a much more general-purpose thing than HTML. For example you can use XML to describe Web pages (like HTML) or to describe non-visual information like a phone book database.

  SGML
FreeMarker Template Language

  Simple programming language designed to write text file templates, especially HTML templates.

FTL
FTL tag

  Tag-like text fragment used to invoke FreeMarker directives in FTL templates. These are similar to HTML or XML tags at the first glance. The most prominent difference is that the tag name is started with `#` or `@`. Another important difference is that FTL tags do not use attributes, but a substantially different syntax to specify parameters. Examples of FTL tags: `<#if newUser>`, `</#if>`, `<@menuitem title="Projects" link="projects.html"/>`

Hash

  A variable that acts as a container that stores subvariables that can be retrieved via a string that is a lookup name.

Line break

  Line break is a special character (or a sequence of special characters) that causes a line breaking when you see the text as plain text (say, when you read the text with Windows notepad). Typically you type this character by hitting ENTER or RETURN key. The line break is represented with different characters on different platforms (to cause incompatibility and confusion...): ``line feed'' character on UNIX-es, ``carriage return'' character on Macintosh, ``carriage return''+``line feed'' (two characters!) on Windows and DOS. Note that line breaks in HTML do not have a visual effect when viewed in a browser; you must use markup such as `<BR>` for that. This manual never means `<BR>` when it says ``line-break''.

Macro definition body

  The template fragment between the `<#macro ...>` and `</#macro>`. This template fragment will be executed when you call the macro (for example as `<@myMacro/>`).

Method

  A variable that calculates something based on parameters you give, and returns the result.

MVC pattern

  MVC stands for Model View Controller. It's a design pattern started his life in the 70's as a framework developer by Trygve Reenskaug for Smalltalk, and was used primary for for UI-s (user interfaces). MVC considers three roles:

  - Model: Model represents application (domain) specific information in a non-visual way. For example, an array of product objects in the memory of your computer is the part of the model.

  - View: View displays the model and provides UI. For example, it's the task of the view component to render the array of product objects to a HTML page.

  - Controller: The controller handles user input, modifies the model, and ensures that the view is updated when needed. For example it is the task of controller to take the incoming HTTP requests, parse the received parameters (forms), dispatch the requests to the proper business logic object, and chose the right template for the HTTP response.

  The most important thing for us when applying MVC for Web applications is the separation of View from the other two roles. This allows the separation of designers (HTML authors) from programmers. Designers deal with the visual aspects, programmers deal with the application logic and other technical issues; everybody works on what he is good at. Designers and programmers are less dependent on each other. Designers can change the appearance without programmers having to change or recompile the program.

  For more information I recommend reading chapter 4.4 of Designing Enterprise Applications with the J2EE Platform blueprint.

Predefined directive

  Directive what is defined by FreeMarker, thus always available. Example of predefined directives: `if`, `list`, `include`

Scalar

  A scalar variable stores a single value. A scalar is either a string or a number or a date/time or a boolean.

Sequence

  A sequence is a variable that contains a sequence of subvariables. The sequence's subvariables are accessible via numerical index, where the index of the very first object is 0, the index of the second objects is 1, the index of the third object is 2, etc.

Regular expression

  A regular expression is a string that specifies a set of strings that matches it. For example, the regular expression `"fo*"` matches `"f"`, `"fo"`, `"foo"`, etc. Regular expressions are used in several languages and other tools. In FreeMarker, the usage of them is a ``power user'' option. So if you have never used them before, there is no need to worry about not being familiar with them. But if you are interested in regular expressions, you can find several Web pages and books about them. FreeMarker uses the variation of regular expressions described at: http://java.sun.com/j2se/1.4.1/docs/api/java/util/regex/Pattern.html

SGML
Standard Generalized Markup Language

  This is an international standard (ISO 8879) that specifies the rules for the creation of platform-independent markup languages. HTML is a markup language created with SGML. XML is a subset (restricted version) of SGML.

  XML
String

  A sequence of characters such as ``m'', ``o'', ``u'', ``s'', ``e''.

Tag

  Text fragment indicating the usage of an element in SGML. Examples of tags: `<body bgcolor=black>`, `</body>`

Template

  A template is a text file with some special character sequences embedded into it. A template processor (e.g. FreeMarker) will interpret special character sequences and it outputs a more or less different text from the original text file, where the differences are often based on a data-model. Thus, the original text acts as a template of the possible outputs.

Template processing job

  A template processing job is the act when FreeMarker merges a template with a data-model to produce the output for a visitor. Note that this may includes the execution of multiple template files because the template file used for the Web page may invokes other templates with `include` and `import` directives. Each template-processing job is a separated cosmos that exists only for the short period of time while the given page is being rendered for the visitor, and then it vanishes with all the variables created in the templates (for example, variables created with `assign`, `macro` or `global` directives).

Transform

  This term refers to user-defined directives that are implemetned with the now obsolete `TemplateTransformModel` Java interface. The feature was originally made for implementing output filters, hence the name.

Thread-safe

  An object is thread-safe if it is safe to call its methods from multiple threads, even in parallel (i.e. multiple threads execute the methods of the object at the same time). Non-thread-safe objects may behave unpredictably in this situation, and generate wrong results, corrupt internal data structures, etc. Thread-safety is typically achieved in two ways with Java: with the usage `synchronized` statement (or `synchronized` methods), and with the immutability of encapsulated data (i.e. you can't modify the field after you have created the object).

User-defined directive

  Directive that is not defined by the FreeMarker core, but by the user. These are typically application domain specific directives, like pull-down menu generation directives, HTML form handling directives.

UCS

  This is international standard (ISO-10646) that defines a huge set of characters and assigns a unique number for each character (``!'' is 33, ..., ``A'' is 61, ``B'' is 62, ..., Arabic letter hamza is 1569... etc.). This character set (not charset) contains almost all characters used today (Latin alphabet, Cyrillic alphabet, Chinese letters, etc.). The idea behind UCS is that we can specify any character with a unique number, not mater what the platform or the language is.

Unicode

  De-facto standard developed by Unicode organization. It deals with the classification of the characters in UCS (which is letter, which is digit, which is uppercase, which is lowercase, etc.), and with other problems of processing text made from the characters of UCS (e.g. normalization).

White-space

  Characters that are totally transparent but have impact on the visual appearance of the text. Examples of white-space characters: space, tab (horizontal and vertical), line breaks (CR and LF), form feed.

XML
Attribute

  In connection with XML or HTML (or SGML in general), attributes are the named values associated with elements. For example, in `<body bgcolor=black text=green>...</body>`, the attributes are `bgcolor=black` and `text=green`. On the left side of `=` is the name of the attribute, while on the right side is the value of the attribute. Note that in XML, the values must be quoted (for example: `<body bgcolor="black" text='green'>`), while in HTML it is optional for certain values.

Full-qualified name

  ... of nodes (XML node or other FTL node variable): The full-qualified name of a node specifies not only the node name (`node?node_name`), but also the node namespace (`node?node_namespace`), this way it unambiguously identify a certain kind of node. The format of the full-qualified name is `nodeName` or `prefix:nodeName`. The prefix is shorthand to identify the node namespace (the a node namespace is usually specified with a long ugly URI). In FTL, prefixes are associated with the node namespaces with the `ns_prefixes` parameter of the `ftl` directive. In XML files, prefixes are associated with the node namespaces with the `xmlns:prefix` attributes. The lack of the prefix means that the node uses the default node namespace, if a default node namespace is defined; otherwise it means that the node does not belong to any node namespace. The default node namespace is defined in FTL by registering reserved prefix `D` with the `ns_prefixes` parameter of the `ftl` directive. In XML files it is defined with attribute `xmlns`.

  ... of Java classes: The full-qualified name of a Java class contains both the class name and the name of the package the class belongs to. This way it unambiguously specifies the class, regardless of the context. An example of full-qualifed class name: `java.util.Map` (as opposed to `Map`).

Alphabetical Index