【发布时间】:2019-04-16 17:35:09
【问题描述】:
我在 Apache Velocity 邮件列表中提出了这个问题,但我没有收到回复,所以我在这里重新发布......
我正在使用新发布的 Apache Velocity 2.1,我正在测试连字符作为标识符名称,但我遇到了错误或什么?我已经设置了 Velocity.PARSER_HYPHEN_ALLOWED 属性,但它只允许用于单个数据,而不是地图或集合数据。
我有这个模板:
hello-world.properties.vm
----------------------------------------------------------
Slash: ${sample-slash}
Slash in a Map: ${map.sample-slash}
我有这个示例测试用例:
public class ApacheVelocityTest {
private final String RESOURCES_DIR = "src/test/resources";
@Test
public void testVelocity() {
Path templatePath = Paths.get(RESOURCES_DIR, "templates", "hello-world.properties.vm");
VelocityEngine ve = new VelocityEngine();
ve.setProperty(Velocity.PARSER_HYPHEN_ALLOWED, true);
ve.init();
Template t = ve.getTemplate(templatePath.toString());
VelocityContext context = new VelocityContext();
context.put("sample-slash", "SLASH");
Map<String, String> sampleData = createData();
context.put("map", sampleData);
StringWriter writer = new StringWriter();
t.merge(context, writer);
System.out.println(writer.toString());
}
public Map<String, String> createData() {
Map<String, String> mapData = new HashMap<String, String>();
mapData.put("sample-slash", "USER1");
return mapData;
}
}
现在,第一个“sample-slash”已正确渲染,但 java 映射中的那个不是..它抛出如下错误:
org.apache.velocity.exception.ParseErrorException: Encountered "-slash}" at src\test\resources\templates\hello-world.properties.vm[line 5, column 22]
Was expecting one of:
"[" ...
"|" ...
"}" ...
"}" ...
at org.apache.velocity.Template.process(Template.java:154)
嵌入到 java 映射中的对象正在抛出解析器异常。
我对此开发人员有任何解决方法吗?非常感谢任何指针。
【问题讨论】:
-
您确实在几个小时后收到了邮件列表上的答复 :-)
-
顺便说一句,感谢您提出问题。
-
这可能是因为点符号主要用于属性,并且(在 Java 字段和方法中)连字符是被禁止的。要访问地图,您应该致电
$map["sample-slash"]velocity.apache.org/engine/2.1/user-guide.html#properties 和 velocity.apache.org/engine/2.1/user-guide.html#index-notation