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:
| |||
Output:
| |||
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:
| |||
the output:
| |||
An inner loop variable can hide an outer loop variable:
| |||
the output:
| |||
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'':
| |||
For information about syntax of variables please read: The Template/Expressions