【发布时间】:2013-08-22 03:48:07
【问题描述】:
解决方案
我之前曾尝试向 LineItem 类添加访问器,例如
public String getItemNo() {
return itemNo;
}
并将 FTL 从 ${lineItem.itemNo} 更改为 ${lineItem.getItemNo()} 但这不起作用。 解决方案是添加访问器,但不更改 FTL(保持为 ${lineItem.itemNo}。
背景
我正在使用 Freemarker 来格式化一些电子邮件。在这封电子邮件中,我需要在发票上列出多行产品信息。我的目标是传递一个对象列表(在地图内),以便我可以在 FTL 中迭代它们。目前我遇到一个问题,我无法从模板中访问对象属性。我可能只是缺少一些小东西,但现在我很难过。
使用 Freemarker 的 Java 类
这是我的代码的更简化版本,以便更快地理解要点。 LineItem 是具有公共属性的公共类(与此处使用的名称匹配),使用简单的构造函数来设置每个值。我也尝试过将私有变量与访问器一起使用,但这也不起作用。
我还将 LineItem 中的 List 对象存储在 Map 中,因为我还将 Map 用于其他键/值对。
Map<String, Object> data = new HashMap<String, Object>();
List<LineItem> lineItems = new ArrayList<LineItem>();
String itemNo = "143";
String quantity = "5";
String option = "Dried";
String unitPrice = "12.95";
String shipping = "0.00";
String tax = "GST";
String totalPrice = "64.75";
lineItems.add(new LineItem(itemNo, quantity, option, unitPrice, shipping, tax, totalPrice));
data.put("lineItems", lineItems);
Writer out = new StringWriter();
template.process(data, out);
超光速
<#list lineItems as lineItem>
<tr>
<td>${lineItem.itemNo}</td>
<td>${lineItem.quantity}</td>
<td>${lineItem.type}</td>
<td>${lineItem.price}</td>
<td>${lineItem.shipping}</td>
<td>${lineItem.gst}</td>
<td>${lineItem.totalPrice}</td>
</tr>
</#list>
错误
FreeMarker template error:
The following has evaluated to null or missing:
==> lineItem.itemNo [in template "template.ftl" at line 88, column 95]
LineItem.java
public class LineItem {
String itemNo;
String quantity;
String type;
String price;
String shipping;
String gst;
String totalPrice;
public LineItem(String itemNo, String quantity, String type, String price,
String shipping, String gst, String totalPrice) {
this.itemNo = itemNo;
this.quantity = quantity;
this.type = type;
this.price = price;
this.shipping = shipping;
this.gst = gst;
this.totalPrice = totalPrice;
}
}
【问题讨论】:
-
我没有发现任何问题。
LineItem类是什么样子的? -
@TomVerelst 添加了类。这是非常基本的。我应该补充一点,在模板处理之前在 Java 类中打印
lineItems数组列表的内容表明属性包含正确的值。 -
感谢您的解决方案。由于它之前对我不起作用的一个问题是我将 Invoice 类作为嵌套/内部类。当我将它作为一个单独的公共课程移出时,它开始工作了。
标签: java freemarker