Apache的Velocity - getTemplate()。如何传递字符串/对象而不是.VM文件?

7

Apache Velocity的getTemplate()方法实际上允许传递.vm文件名,我能否在此处传递字符串/对象?是否有可用的方法来传递字符串/对象?


可能是如何使用字符串作为Velocity模板?的重复。 - Toparvion
3个回答

3

这是我正在使用的示例代码。
Velocity版本:1.7
我使用log4j作为日志记录器。

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.loader.StringResourceLoader;
import org.apache.velocity.runtime.resource.util.StringResourceRepository;


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

我们可以同时使用类资源加载器和字符串资源加载器吗? - Asad Shakeel

2

尝试了所有测试,但在Velocity 1.7中全部失败! - Jurica Krizanic

1

请查看StringResourceLoader


我找到了一个StringResourceLoader的例子。http://velocity.apache.org/engine/devel/apidocs/org/apache/velocity/runtime/resource/loader/StringResourceLoader.html。但我们的模板信息是以字符串形式存在的。我们需要传递字符串而不是.vm文件。对于这种情况,我该怎么做?如果有任何示例代码,请提供。 - vasantharajan
1
StringResourceLoader允许您直接将模板添加到存储库中,然后像其他模板一样检索它们。StringResourceLoader.getRepository().putStringResource(myTemplateName, myTemplateString); - Nathan Bubna
StringResourceLoader.getRepository() 返回 null。有没有可以设置的属性? - Asad Shakeel
好久不见了。可能应该配置VelocityEngine并使用它,首先要用以下属性初始化引擎: resource.loader = stringstring.resource.loader.class = org.apache.velocity.runtime.resource.loader.StringResourceLoader - Nathan Bubna

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接