How to use String as Velocity Template?

后端 未结 5 1546
庸人自扰
庸人自扰 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条回答
  •  Happy的楠姐
    2020-12-08 04:25

    The above sample code is working for me. It uses Velocity version 1.7 and 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());
    }
    

    A similar so question.

提交回复
热议问题