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

新手上路,请多包涵

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

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

原文由 tomsame 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 423
2 个回答

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

 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();

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

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

原文由 ZZ Coder 发布,翻译遵循 CC BY-SA 3.0 许可协议

上面的示例代码对我有用。它使用 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());
}

一个 类似 的问题。

原文由 Georgios Syngouroglou 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题