簡體   English   中英

速度無法解析foreach循環中的變量

[英]Velocity does not resolve variable in foreach loop

我有一個非常簡單的速度模板:

<html>
    <head>
        <title>Velocity template</title>
    </head>
    <body>      
        #foreach($p in $products)
            $p.name
        #end        
    </body>
</html>

和處理它的代碼:

VelocityEngine engine = new VelocityEngine();
engine.init();
Template t = engine.getTemplate("./src/com/irbis/dms/velocity/template.html");
VelocityContext ctx = new VelocityContext();

Product p1 = new Product("fridge");
Product p2 = new Product("sofa");
Product p3 = new Product("table");
Product p4 = new Product("chair");

List<Product> products = new ArrayList<Product>();
products.add(p1);
products.add(p2);
products.add(p3);
products.add(p4);

ctx.put("products", products);
...

class Product implements Serializable {

    private String name;

    public Product() {
    }

    public Product(String name) {
        super();
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

但是執行后,我有以下內容:

<html>
    <head>
        <title>Velocity template</title>
    </head>
    <body>      
                    $p.name
                    $p.name
                    $p.name
                    $p.name
    </body>
</html>

如果將上下文放入String,Integer等,則效果很好。錯誤在哪里? 我使用速度1.5。

您必須將Product類聲明為public ,否則您將無法在模板中使用它。

public class Product implements Serializable {

您的變量是私有變量,因此不可見,請使用getName()並告知我們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM