0

以下是我想要做的一个例子。我有一堆文件,例如 test1.vm:

Welcome ${name}. This is test1.

然后我有一个名为 defaults.vm 的文件:

#set($name = "nmore")

我想在不使用 #parse 的情况下使用 defaults.vm 中的变量渲染 test1.vm(和其他测试文件),因为我必须修改所有测试文件。

有没有办法从随附的 java 文件中执行此操作?

4

1 回答 1

4

I'm not sure if you have any constraints or any other specific requirements, but if you don't have you tried to use Velocity API? Something like this:

Context context = new VelocityContext();

Template template = Velocity.getTemplate("src/main/resources/defaults.vm");
template.merge(context, NullWriter.NULL_WRITER);

StringWriter writer = new StringWriter();
Template toBeParsedTemplate = Velocity.getTemplate("src/main/resources/test1.vm");
toBeParsedTemplate.merge(context, writer);

String renderedContent = writer.getBuffer().toString();
System.out.println(renderedContent);

The idea is that you fill in the Context object with the variables generated from defaults.vm and use the same context to evaluate test1.vm.

I've tried this using Velocity 1.7 and commons-io 2.4 (for the NullWriter) seems to be working fine, but I'm not sure if this can fit into your requirement or you're looking into other alternatvies (not using Velocity API).

More info on the Context object here:
http://velocity.apache.org/engine/devel/developer-guide.html#The_Context

Hope that helps.

于 2013-07-10T03:16:17.367 回答