each

用途

用Groovy JDK each 方法,迭代对象里的每个元素.

示例

<g:each in="${books}">
     <p>Title: ${it.title}</p>
     <p>Author: ${it.author}</p>
</g:each>

命名 item:

<g:each var="book" in="${books}">
     <p>Title: ${book.title}</p>
     <p>Author: ${book.author}</p>
</g:each>

literal 必需内付在括号里:

<ul>
  <g:each var="i" in="${ (0..<100) }>
    <li>Item ${i}</li>
  </g:each>
</ul>

另一例子,item 必需被命名 (否则,不能访问title属性):

<g:each in="${itemList}" var="item">
	<g:link action="show" id="${item.id}">${item.title}</g:link>
</g:each>

用 status 参数确定表格中不同行使用不同的样式:

<tbody>
  <g:each status="i" in="${itemList}" var="item">
    <!-- Alternate CSS classes for the rows. -->
    <tr class="${ (i % 2) == 0 ? 'a' : 'b'}">
      <td>${item.id?.encodeAsHTML()}</td>
      <td>${item.parentId?.encodeAsHTML()}</td>
      <td>${item.type?.encodeAsHTML()}</td>
      <td>${item.status?.encodeAsHTML()}</td>
    </tr>
  </g:each>
</tbody>

描述

属性

  1. in - 迭代的对象
  2. status (可选) - 变量的名称用来存储 in 中的迭代索引. 这个变量第一个索引值是0,下一个是1,依次类推.如果这个变量被使用, var 也是必需的.
  3. var (this) - item 的名称, 默认是 "it".

注意的是 :在GSP动态标签body中,当迭代的值被使用,var 属性必需被指定 . 例如: <g:link>.