2011-06-29 80 views

回答

1

看看我搜索了在同一個問題小時StringResourceLoader

+0

我發現一個StringResourceLoader的例子。 http://velocity.apache.org/engine/devel/apidocs/org/apache/velocity/runtime/resource/loader/StringResourceLoader.html。但是我們正在將字符串formmate中的模板信息。我們需要傳遞字符串而不是.vm。我應該爲這種情況做些什麼。請如果有任何示例代碼。 – vasantharajan

+1

StringResourceLoader允許您直接將模板添加到存儲庫,然後像其他任何模板一樣檢索它們。 StringResourceLoader.getRepository()。putStringResource(myTemplateName,myTemplateString); –

2

這是爲我工作的一個示例代碼。
速度版本: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()); 
} 
相關問題