${foreach} - the terp iterator

<${if} Statement ${switch} Statement >

The foreach statement allows you to iterate over the elements of a collection or an array. Every foreach statement needs to be terminated by a matching end or endforeach statement. The statements in-between are expended once for every element of the collection.

You don't always need to use foreach. When you have a collection, you can just reference it in an embedded expression and the end result will be the concatenation of the elements' string representations. This is perfectly sufficient for many use cases and demonstrated in the example below.

C:\terp\bin>terp -t "${{0,1,2,3}}"

In other cases, you might need to perform some more complex formatting on the collection elements. You might get away with a join formatter that allows you to optionally specify the separator between elements, for example a space:

C:\terp\bin>terp -t "${{0,1,2,3}[join(' ')]}"
0 1 2 3

You can use any separator you like, not just single characters.

When even that does not suffice, you can use an embedded foreach statement. The ${eol}

C:\terp\bin>terp -t "${foreach(i:{0,1,2,3})}(byte)${i}${eol}${end}"

A foreach statement is a scoped statement, i.e. a statement that is terminated by an ${end} statement. It applies the template nested between the beginning and the end statement to every element in the collection. Typically, you will reference the element at least once via the variable name denoting the element.

The foreach element's expansion is affected by by several optional metadata elements, chief among them foreach.prefix, foreach.suffix, and foreach.sep. During expansion, the prefix element is inserted before the first element of the enumeration and the suffix element is appended to the last element of the enumeration. The separator element is inserted between enumeration elements. All three elements have in common that they are only applied to non-empty enumerations. The following example illustrates how you can have a space before the first element, a space after the last element, and a comma and a space between elements:

C:\terp\bin>terp -t "(${foreach(i:{0,1,2,3}) #foreach.prefix=' ' 
#foreach.suffix=' ' #foreach.sep=', '}(byte)${i}${end})" ( (byte)0, (byte)1, (byte)2, (byte)3 ) C:\terp\bin>

In the following example we are using every element in the collection twice, once as a URL and once as the text being displayed in a link. The links are added to a list.

${foreach(link:collection)}    <li><a href="${link}">${link}</a></li>

You can also use foreach in ant scripts to loop over collection elements. Please see the <terp.foreach> task's documentation.

Copyright 2006-2016 by Codemesh, Inc., ALL RIGHTS RESERVED

terp template statements
codemesh.com home expressions templates ant about us contact us download