Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Velocity does not resolve variable in foreach loop

I have very simple velocity template:

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

and code that processes it:

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;
    }
}

but after the execution I have the following:

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

It works fine if I put into the context String, Integer etc. Where is the error? I use velocity 1.5.

like image 221
hard-code Avatar asked May 24 '13 09:05

hard-code


1 Answers

You have to declare your Product class as public or otherwise you can not use it in your template.

public class Product implements Serializable {
like image 171
Marco Forberg Avatar answered Sep 23 '22 15:09

Marco Forberg