2009. 11. 24. 19:18

[FreeMarker] list, break

원문: http://freemarker.sourceforge.net/docs/ref_directive_list.html

Synopsis

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

여기서 
  • sequence: expression evaluates to a sequence or collection
  • item: loop variable(expression 이 아님)의 이름
Description

sequence 의 각 variable 에 대해 template section 을 처리하기 위해 list 명령어를 사용할 수 있습니다. 시작 태그와 종료 태그 사이의 코드는 1번째 subvariable, 2번째 subvariable, 3번째 subvariable, ..., 마지막 subvariable 에 대해 처리될 것입니다. 각 iteration 마다 loop variable 은 각 iteration 에서의 subvariable 의 값을 가집니다.

list loop 안에서 두 가지 특별한 loop variable 을 사용할 수 있습니다:
  • item_index: 이 variable 은 item 의 인덱스입니다.
  • item_has_next: item 이 sequence 의 마지막인지 아닌지 알려주는 boolean 값입니다.
예제 1:
<#assign seq = ["winter", "spring", "summer", "autumn"]> <#list seq as x> ${x_index + 1}. ${x}<#if x_has_next>,</#if> </#list>

결과:
1. winter, 2. spring, 3. summer, 4. autumn

예제 2: numerical range sequence expression 을 이용하여, 두 숫자 사이를 세기 위해 list 를 사용할 수 있습니다.
<#assign x=3> <#list 1..x as i> ${i} </#list>

결과:
1 2 3

x 가 0 이면 위의 예제가 예상되로 실행되지 않고, 0 과 -1 을 출력할 것입니다.

break 명령어를 사용하면 sequence 의 마지막 subvariable 을 통과하기 전에 list loop 을 벗어날 수 있습니다. 예를 들어 아래의 코드는 "winter" 와 "spring" 만을 출력합니다:
<#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 listand 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' 카테고리의 다른 글

[FreeMarker] Built-ins for strings  (0) 2009.01.07