assign

Synopsis

<#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:

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: Template Author's Guide/Miscellaneous/Defining variables in the template

Note:

A frequent mistake is trying to use assign to change a local variable like: <#macro m><#local x = 1>${x}<#assign x = 2>${x}</#macro>. This prints 11, not 12, because assign creates/replaces the x of the namespace that the template belongs to, and doesn't change the x local variable. Local variables should be always set with the local directive, not just for the fist time.

Example: variable seq will store a sequence:

<#assign seq = ["foo", "bar", "baz"]>

Example: Increments the numerical value stored in variable x:

<#assign x++>

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
  seq = ["foo", "bar", "baz"]
  x++
>

If you know what namespaces are: assign directive creates variables in a namespace. 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}!">
上一章 首页 下一章