【问题标题】:Velocity does not resolve variable in foreach loop速度不能解析 foreach 循环中的变量
【发布时间】:2013-05-24 09:48:11
【问题描述】:

我有一个非常简单的速度模板:

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

如果我将字符串、整数等放入上下文中,它可以正常工作。 错误在哪里?我使用速度 1.5。

【问题讨论】:

  • 您是否将class Product 声明为公开?
  • 非常感谢!问题是class Product 被声明为具有默认访问权限。现在它工作正常。
  • Marco,你能发表你的答案吗?所以我可以将其标记为已接受
  • 如果它让你开心 ;)
  • 这是我第一次使用 Velocity,这是一个奇迹,感谢 Marco

标签: java foreach velocity


【解决方案1】:

您必须将Product 类声明为public,否则您不能在模板中使用它。

public class Product implements Serializable {

【讨论】:

  • Velocity 的行为非常糟糕,我敢说。
  • 问题在于 Velocity 的沉默。如果它抱怨这样的事情会更容易......
【解决方案2】:

您的变量不可见,因为它是私有的,请使用 getName() 并告诉我们。

【讨论】:

  • 那就学点新东西吧!
猜你喜欢
  • 2021-01-25
  • 1970-01-01
  • 1970-01-01
  • 2014-06-18
  • 1970-01-01
  • 2021-12-02
  • 2021-05-21
  • 2014-05-27
相关资源
最近更新 更多