Velocity 没有用 VelocityContext 替换 Template 的变量

Velocity does not replace Template's variables with VelocityContext

我是 Velocity 的新手,发现模板的变量没有被我放入 VelocityContext 的值替换很奇怪。

代码是这样的

import java.io.StringWriter;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;

public class Main {
public static void main(String args[]){
    People XiaoMing=new People("XiaoMing", 11);
    VelocityEngine engine=new VelocityEngine();
    Template template=engine.getTemplate("/src/main/java/VMTemplate.vm");
    VelocityContext context=new VelocityContext();
    context.put("People", XiaoMing);
    StringWriter sw=new StringWriter(10000);
    template.merge(context, sw);
    System.out.println(sw.toString());
    }
}

class People{
  private String name;
  private int age;
  public People(String name,int age){
      this.name=name;
      this.age=age;
  }

  public String getName(){
      return name;
  }

  public int getAge(){
      return age;
   }
}

模板如下所示。

#set($Name=$People.getName())
#set($Age=$People.getAge())

He is a $Age years old guy,and his name is $Name.

我不知道出了什么问题。能帮我查一下吗?

非常感谢!

我相信你有一些模板后的语法是

VelocityContext context = new VelocityContext();
context.put("Name", XiaoMing.getName());

小明是人物对象,不是字符串。

终于找到模板中对象没有被替换的原因了

只有public可以解析对象。 因此我只需要创建一个public class 名为Xiaoming.

我遇到过类似的问题。 如果您使用自定义字段,则不需要上下文提供程序。 相反,覆盖 AbstractCustomFieldType 的 getVelocityParameters(),它 returns 一个映射。

还有一个问题是空格不能在 # 之前 #foreach 开始,等等,不知道为什么。