For set:
[#set name=value]
or
[#set name1=value1 name2=value2 ... nameN=valueN]
or
[#set same as above... in namespacehash]
or
[#set name]
capture this
[/#set]
or
[#set name in namespacehash]
capture this
[/#set]
For var:
[#var name]
or
[#var name1, name2, ... nameN]
or
[#var name=value]
or
[#var name1=value1 name2=value2 ... nameN=valueN]
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 [#set
"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.
These directives are available since FreeMarker 2.4. They
replace these FreeMarker 2.3 directives: assign,
local and
global.
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: Template Author's Guide/Miscellaneous/Defining variables in the template
Example: variable seasons will store a
sequence:
 |  |  |
 | [#set seasons = ["winter", "spring", "summer", "autumn"]] |
|  |
 |  |  |
Example: Increments the numerical value stored in variable
test:
As a convenience feature, you can do more assignments with one
set tag. For example this will do the same as the
two previous examples:
 |  |  |
 | [#set
seasons = ["winter", "spring", "summer", "autumn"]
test = test + 1
] |
|  |
 |  |  |
If you know what namespaces are: unless the variable has been
declared as "scoped", the set directive creates
variables in the current namespace. 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]
[#set bgColor="red" in my] |
|  |
 |  |  |
An extreme usage of set 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]
[#set x]
[#list 1..3 as n]
${n} [@myMacro /]
[/#list]
[/#set]
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:
 |  |  |
 | [#set x]Hello ${user}![/#set]; [#-- BAD PRACTICE! --] |
|  |
 |  |  |
You should simply write:
 |  |  |
 | [#set x="Hello ${user}!"] |
|  |
 |  |  |