将速度模板中的java对象列表显示为html表

时间:2013-03-21 10:51:56

标签: java velocity

我从DB获取对象列表。我想使用速度模板将它们填充到html表中。

<table>
<thead>
<tr>
<td>$value1 </td>
<td>$value2 </td>
</tr>
</thead>
<tbody>
<!-- Iterate through the list (List<SomeObject>) and display them here,   -->
</tbody>
</table>

对于标题我使用下面的代码,

VelocityContext context = new VelocityContext();
context.put("value1", "text1");
context.put("value2", "text2");

我从对象获取数据,如下所示

List<SomeObject> obj = new ArrayList<SomeObject>();
obj.getItem1();
obj.getItem2();

所有单独的项目都是字符串。如何填充表体内容?

1 个答案:

答案 0 :(得分:9)

尝试以下方法:

<tbody>
#foreach( $obj in $objs )
    <tr><td>$obj.Item1</td><td>$obj.Item2</td></tr>
#end
<tbody>

我假设您的列表放在名为objs的速度上下文中,而您的SomeObject类有2个字段:item1和item2以及相应的getter。

List<SomeObject> objs = ... //prepopulated
context.put("objs", objs);

详情请见velocity documentation