简体   繁体   中英

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:

Welcome ${name}. This is test1.

Then I have a file called 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.

Is there a way to do this from within the accompanying java file?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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