简体   繁体   English

在Java中解析速度变量

[英]Parse velocity variables within java

The following is an example of what I want to do. 以下是我想做的一个例子。 I have a bunch of files such as test1.vm: 我有一堆文件,例如test1.vm:

Welcome ${name}. This is test1.

Then I have a file called defaults.vm: 然后,我有一个名为defaults.vm的文件:

#set($name = "nmore")

I want render test1.vm (and the other test files) with the variable(s) in defaults.vm without using #parse as I would have to modify all the test files. 我想要使​​用defaults.vm中的变量渲染test1.vm(和其他测试文件),而不使用#parse,因为我必须修改所有测试文件。

Is there a way to do this from within the accompanying java file? 有没有办法从随附的Java文件中执行此操作?

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? 我不确定您是否有任何约束或其他特定要求,但是如果您没有尝试使用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 . 这个想法是用从defaults.vm生成的变量填充Context对象,并使用相同的上下文来评估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). 我已经尝试使用Velocity 1.7和commons-io 2.4(对于NullWriter )运行良好,但是我不确定这是否可以满足您的要求,或者您是否正在寻找其他替代品(不使用Velocity API) )。

More info on the Context object here: 有关Context对象的更多信息,请Context
http://velocity.apache.org/engine/devel/developer-guide.html#The_Context http://velocity.apache.org/engine/devel/developer-guide.html#The_Context

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM