Java 如何使用字符串作为速度模板?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1432468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:01:21  来源:igfitidea点击:

How to use String as Velocity Template?

javavelocity

提问by tomsame

What is the best way to create Velocity Template from a String?

从字符串创建速度模板的最佳方法是什么?

I'm aware of Velocity.evaluatemethod where I can pass String or StringReader, but I'm curios is there a better way to do it (e.g. any advantage of creating an instance of Template).

我知道Velocity.evaluate方法,我可以在其中传递 String 或 StringReader,但我很好奇有没有更好的方法来做到这一点(例如,创建模板实例的任何优势)。

采纳答案by ZZ Coder

There is some overhead parsing template. You might see some performance gain by pre-parsing the template if your template is large and you use it repeatedly. You can do something like this,

有一些开销解析模板。如果您的模板很大并且您重复使用它,您可能会通过预解析模板看到一些性能提升。你可以做这样的事情,

RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
StringReader reader = new StringReader(bufferForYourTemplate);
Template template = new Template();
template.setRuntimeServices(runtimeServices);

/*
 * The following line works for Velocity version up to 1.7
 * For version 2, replace "Template name" with the variable, template
 */
template.setData(runtimeServices.parse(reader, "Template name")));

template.initDocument();

Then you can call template.merge()over and over again without parsing it everytime.

然后你可以template.merge()一遍又一遍地调用而不必每次都解析它。

BTW, you can pass String directly to Velocity.evaluate().

顺便说一句,您可以将 String 直接传递给Velocity.evaluate().

回答by George Siggouroglou

The above sample code is working for me. It uses Velocity version 1.7 and log4j.

上面的示例代码对我有用。它使用 Velocity 1.7 版和 log4j。

private static void velocityWithStringTemplateExample() {
    // Initialize the engine.
    VelocityEngine engine = new VelocityEngine();
    engine.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute");
    engine.setProperty("runtime.log.logsystem.log4j.logger", LOGGER.getName());
    engine.setProperty(Velocity.RESOURCE_LOADER, "string");
    engine.addProperty("string.resource.loader.class", StringResourceLoader.class.getName());
    engine.addProperty("string.resource.loader.repository.static", "false");
    //  engine.addProperty("string.resource.loader.modificationCheckInterval", "1");
    engine.init();

    // Initialize my template repository. You can replace the "Hello $w" with your String.
    StringResourceRepository repo = (StringResourceRepository) engine.getApplicationAttribute(StringResourceLoader.REPOSITORY_NAME_DEFAULT);
    repo.putStringResource("woogie2", "Hello $w");

    // Set parameters for my template.
    VelocityContext context = new VelocityContext();
    context.put("w", "world!");

    // Get and merge the template with my parameters.
    Template template = engine.getTemplate("woogie2");
    StringWriter writer = new StringWriter();
    template.merge(context, writer);

    // Show the result.
    System.out.println(writer.toString());
}

A similarso question.

一个类似的问题。

回答by user7294900

Velocity 2 can be integrated into the JSR223 Java Scripting Language Frameworkwhich make another option to transform string as a template:

Velocity 2 可以集成到 JSR223 Java 脚本语言框架中,这为将字符串转换为模板提供了另一种选择:

ScriptEngineManager manager = new ScriptEngineManager();
manager.registerEngineName("velocity", new VelocityScriptEngineFactory());
ScriptEngine engine = manager.getEngineByName("velocity");


System.setProperty(VelocityScriptEngine.VELOCITY_PROPERTIES, "path/to/velocity.properties");
String script = "Hello $world";
Writer writer = new StringWriter();
engine.getContext().setWriter(writer);
Object result = engine.eval(script);
System.out.println(writer);

回答by otmek

RuntimeServices rs = RuntimeSingleton.getRuntimeServices();            
StringReader sr = new StringReader("Username is $username");
SimpleNode sn = rs.parse(sr, "User Information");

Template t = new Template();
    t.setRuntimeServices(rs);
    t.setData(sn);
    t.initDocument();

VelocityContext vc = new VelocityContext();
vc.put("username", "John");

StringWriter sw = new StringWriter();
t.merge(vc, sw);

System.out.println(sw.toString());

回答by devatherock

This works in Velocity 2.1

这适用于 Velocity 2.1

// Initialize the engine
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.setProperty(Velocity.RESOURCE_LOADERS, "string");
velocityEngine.setProperty("resource.loader.string.class", StringResourceLoader.class.getName());
velocityEngine.init();

// Add template to repository
StringResourceRepository repository = StringResourceLoader.getRepository()
repository.putStringResource("hello_world", "Hello $w");

// Set parameters
VelocityContext context = new VelocityContext();
context.put("w", "world!");

// Process the template
StringWriter writer = new StringWriter();
velocityEngine.getTemplate('hello_world').merge( context, writer );

System.out.println(writer.toString());