Variables, scopes - Apache FreeMarker Manual

Unsupported web browser - Use a modern browser to view this website!

- Home
- Manual
- Java API

- Contribute
- Report a Bug
- Download

Manual
Previous Next

# Variables, scopes

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.

Previous Next