访问<#list>中的对象的属性



解决方案

我以前尝试过向LineItem类添加访问者,比如

public String getItemNo() {
    return itemNo;
}

将FTL从CCD_ 1改为CCD_解决方案是添加访问者,但更改FTL(保持为${lineItem.itemNo}

背景

我正在使用Freemark来格式化一些电子邮件。在这封电子邮件中,我被要求列出许多行的产品信息,比如发票上的信息。我的目标是传递一个对象列表(在Map中),这样我就可以在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);

FTL

<#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类的所有属性都缺少getter方法。因此,弗里马克找不到他们。您应该为LineItem的每个属性添加一个getter方法。

对我来说,将${lineItem.itemNo}0添加到模型中起到了关键作用。