如何从 Java 调用存储在 Velocity 模板中的velocityMacro
我想从我的 Java 应用程序调用 Velocity 模板文件中定义的宏。
例如,我在名为 helloworld.vm
的模板文件中定义了以下宏:
#macro( print $msg $n )
#foreach( $i in [1..$n] )
Hello ${msg}!
#end
#end
然后,我想使用速度引擎来执行特定的宏:
velocityEngine = new VelocityEngine();
velocityEngine.setProperty("resource.loader", "class");
velocityEngine.setProperty("class.resource.loader.class", ClassLoaderResourceLoader.class.getName());
velocityEngine.setProperty("class.resource.loader.classloader", this.classLoader);
velocityEngine.setProperty("class.resource.loader.location", "PATH_TO_TEMPLATE_DIRECTORY");
velocityEngine.init();
velocityContext = new VelocityContext();
StringWriter sw = new StringWriter();
velocityContext.put("msg", "Tom");
velocityContext.put("n", 2);
velocityEngine.invokeVelocimacro("print", "print", new String[]{"msg","n"}, velocityContext, sw);
我希望将其提供给 sw
类似:
Hello Tom!
Hello Tom!
而是产生以下错误:
RuntimeInstance.invokeVelocimacro() : VM 'print' is not registered.
因此,注册速度宏的过程是什么,或者是否有其他方法从 Java 调用存储在自定义模板文件中的速度宏?
I would like to invoke a macro defined in a Velocity template file from my Java application.
For example, I defined the following macro in a template file named helloworld.vm
:
#macro( print $msg $n )
#foreach( $i in [1..$n] )
Hello ${msg}!
#end
#end
And then, I would like to use the velocity engine to execute a specific macro:
velocityEngine = new VelocityEngine();
velocityEngine.setProperty("resource.loader", "class");
velocityEngine.setProperty("class.resource.loader.class", ClassLoaderResourceLoader.class.getName());
velocityEngine.setProperty("class.resource.loader.classloader", this.classLoader);
velocityEngine.setProperty("class.resource.loader.location", "PATH_TO_TEMPLATE_DIRECTORY");
velocityEngine.init();
velocityContext = new VelocityContext();
StringWriter sw = new StringWriter();
velocityContext.put("msg", "Tom");
velocityContext.put("n", 2);
velocityEngine.invokeVelocimacro("print", "print", new String[]{"msg","n"}, velocityContext, sw);
Which I would expect to feed sw
with something like:
Hello Tom!
Hello Tom!
But rather produces the following error:
RuntimeInstance.invokeVelocimacro() : VM 'print' is not registered.
Therefore, what is the procedure for registering a velocityMacro or is there any other way of invoking a Velocity macro stored in a custom template file from Java?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我相信您还需要指定属性
resource.loader=class
以便 Velocity 使用基于类加载器的加载器。请参阅
ClasspathResourceLoader< /code>javadocs
。
另外,这个模板文件实际上在类路径中吗?
I believe you need to also specify the property
resource.loader=class
in order for Velocity to use the classloader-based loader.See the
ClasspathResourceLoader
javadocs.In addition, is this template file actually on the classpath?