list, break

Page Contents

Synopsis

<#list sequence as item>
    ...
</#list>

Where:

Description

You can use the list directive to process a section of template for each variable contained within a sequence. The code between the start-tag and end-tag will be processed for the 1st subvariable, then for the 2nd subvariable, then for the 3rd subvariable, etc until it passes the last one. For each such iteration the loop variable will contain the current subvariable.

There are two special loop variables available inside the list loop:

Example 1:

<#assign seq = ["winter", "spring", "summer", "autumn"]>
<#list seq as x>
  ${x_index + 1}. ${x}<#if x_has_next>,</#if>
</#list>  

will output:

  1. winter,
  2. spring,
  3. summer,
  4. autumn  

Example 2: You can use list to count between two numbers, using a numerical range sequence expression:

<#assign x=3>
<#list 1..x as i>
  ${i}
</#list>  

The output will be:

  1
  2
  3
   

Note that the above example will not work as you may expected if x is 0, as then it will print 0 and -1.

You can leave the list loop before it passes the last subvariable of the sequence with the break directive. For example this will print ``winter'' and ``spring'' only:

<#list seq as x>
  ${x}
  <#if x = "spring"><#break></#if>
</#list>  

Note that if you turn on the classic compatible mode, then the list accepts a scalar as well and treats it as a single-element sequence.

In general, it is best to avoid using collection that wraps an Iterator as parameters to list and use collection that wraps java.util.Collection or sequence whenever possible. There are situations however, when you only have an Iterator at your disposal. Note that if you pass an collection that wraps an Iterator to the list, you can iterate over its elements only once since Iterators are by their nature one-off objects. When you try to list a such collection variable for the second time, an error will abort template processing.

FreeMarker Manual -- For FreeMarker 2.3.22
HTML generated: 2015-02-28 21:34:03 GMT
Edited with XMLMind XML Editor
Here!