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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15545431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:00:41  来源:igfitidea点击:

Display a list of java objects in velocity templates as html table

javavelocity

提问by NEO

I am fetching a list of objects from DB. I would like to populate them in to a html table using velocity templates.

我正在从数据库中获取对象列表。我想使用速度模板将它们填充到 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>

For headers I am using the below code,

对于标题,我使用以下代码,

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

I get data from objects as below,

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

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

All the individual items are Strings. How to populate the table body content?

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

回答by dcernahoschi

Try the following:

请尝试以下操作:

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

I assume that your list is put on the velocity context under the name objsand your SomeObjectclass has 2 fields: item1 and item2 with coresponding getters.

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

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

See more on the velocity documentation.

请参阅有关速度文档的更多信息