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:

  • In the Environment:

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

  • 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.

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

  • 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.

  • In the data-model object you have passed to the process method

  • 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.

Updated at: 7 months ago
MiscellaneousTable of contentCharset issues