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

标签 java velocity

Apache 的 Velocity — getTemplate()。实际上它允许传递 .vm 文件名,我可以在这里传递字符串/对象吗?是否有任何方法可用于传递字符串/对象?

最佳答案

这是适合我的示例代码。
极速版本: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());
}

关于java - Apache 的 Velocity — getTemplate() 。如何传递字符串/对象而不是 .VM 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6521871/

相关文章:

java - 传递一个类并返回不同的类作为 java 泛型方法的返回对象

java - 未找到速度模板

java - 如何编写更改控制面板主题配色方案的插件?

java - 如何将所有输入转义到 Velocity 模板

c# - 编译 c++/c#/java 有何不同?

java - java中如何在不使用长度的情况下计算字符数?

java - Java Swing 的错误消息

java - 一次执行HDFS读写操作

java - Apache 速度 : ReourceNotFoundException in simple example

testing - 将黑猩猩与 Meteor 一起使用时固定装置的正确方法是什么