How to use String as Velocity Template?

后端 未结 5 1570
庸人自扰
庸人自扰 2020-12-08 03:48

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

I\'m aware of Velocity.evaluate method where I can pass String or StringReader, but I\'m cur

5条回答
  •  天涯浪人
    2020-12-08 04:23

    This works in 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());
    

提交回复
热议问题