如何在Velocity模板中打印对象列表? [英] How to print a list of objects in a Velocity template?

查看:381
本文介绍了如何在Velocity模板中打印对象列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常基本的问题,我敢肯定我做错了事或做了一些假设.来了.

This is a pretty basic problem and I'm pretty sure I'm doing something wrong or making some assumption. Here goes.

我正在编写一个使用速度模板系统的Jira插件.我有一个ResultRow对象的列表,其中ResultRow是具有单个成员变量的类:字符串键:

I'm writing a Jira plugin, which uses the Velocity template system. I have a list of ResultRow objects where ResultRow is a class with a single member variable: String key:

public class ResultRow {
  public String key;
}

我有这些ResultRows的列表:

I have a list of these ResultRows:

List<ResultRow> rows = new ArrayList<ResultRow>();

ResultRow row = new ResultRow();
row.key = "foo";

rows.add(foo);

Map<String, Object> velocityParams = new HashMap<String, Object>();
velocityParams.put("rows", rows);

return descriptor.getHtml("view", velocityParams);

并且我正在尝试使用以下命令在模板中列出这些行:

and I am trying to list these rows in a template with the following:

#foreach ($row in $rows)
  <tr><td>$row.key</td></tr>
#end

我希望输出为:foo.令人疯狂的是,模板系统仅打印文字字符串"$ row.key"而不是键的内容.为了验证"$ row"确实是一个对象,我使用了模板:

I want the output to be: foo. Maddeningly, the template system simply prints the literal string "$row.key" instead of the contents of key. To verify that "$row" is indeed an object, I used the template:

#foreach ($row in $rows)
  <tr><td>$row</td></tr>
#end

结果与预期的一样:com.domain.jira.ResultRow@7933f2c6.

and the result was as expected: com.domain.jira.ResultRow@7933f2c6.

我认为也许我缺少该课程的某些要求.是否需要以某种特殊的方式定义它以向Velocity建议某些成员可在模板中使用?吉拉(Jira)是否使用某些仅适用于某些对象的特别时髦的Velocity版本?

I think maybe I'm missing some requirement for the class. Does it need to be defined in some special way to suggest to Velocity that certain members are usable in templates? Does Jira use some special funky version of Velocity that only works with certain objects?

推荐答案

Velocity不公开字段,仅公开方法.有多种方法可以改变这种情况:

Velocity does not expose fields, only methods. There are ways to change that:

  • 您可以创建自己的允许访问公共字段的Uberspect类.

  • You can create your own Uberspect class that allows access to public fields.

您可以使用Velocity的FieldMethodizer的修改版本包装实例,该版本可以访问非静态字段.

You can wrap the instance with a modified version of Velocity's FieldMethodizer that gives access to non-static fields.

您可以在上下文中添加和使用工具"类的实例,例如VelocityTool的ClassTool的子类.

You can add and use an instance of a "tool" class to your context, such as a subclass of VelocityTool's ClassTool.

这篇关于如何在Velocity模板中打印对象列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆