Pergunta

Qual é a melhor maneira de criar modelo Velocity de um String?

Eu estou ciente de Velocity.evaluate método onde eu posso passar string ou StringReader, mas estou curiosa se existe uma maneira melhor de fazê-lo (por exemplo, qualquer vantagem de criar uma instância de Template ).

Foi útil?

Solução

Há algum modelo de análise em cima. Você pode ver alguns ganho de desempenho por pré-análise do modelo, se o seu modelo é grande e você usá-lo repetidamente. Você pode fazer algo como isso,

RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices();
StringReader reader = new StringReader(bufferForYourTemplate);
Template template = new Template();
template.setRuntimeServices(runtimeServices);

/*
 * The following line works for Velocity version up to 1.7
 * For version 2, replace "Template name" with the variable, template
 */
template.setData(runtimeServices.parse(reader, "Template name")));

template.initDocument();

Em seguida, você pode chamar template.merge() uma e outra vez, sem analisá-lo sempre.

BTW, você pode passar cordas diretamente para Velocity.evaluate().

Outras dicas

O código de exemplo acima está funcionando para mim. Ele usa Velocity versão 1.7 e 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 semelhante de modo questão.

Velocity 2 pode ser integrado no JSR223 Java Scripting Language quadro que fazem outra opção para transformar string como um modelo:

ScriptEngineManager manager = new ScriptEngineManager();
manager.registerEngineName("velocity", new VelocityScriptEngineFactory());
ScriptEngine engine = manager.getEngineByName("velocity");


System.setProperty(VelocityScriptEngine.VELOCITY_PROPERTIES, "path/to/velocity.properties");
String script = "Hello $world";
Writer writer = new StringWriter();
engine.getContext().setWriter(writer);
Object result = engine.eval(script);
System.out.println(writer);
RuntimeServices rs = RuntimeSingleton.getRuntimeServices();            
StringReader sr = new StringReader("Username is $username");
SimpleNode sn = rs.parse(sr, "User Information");

Template t = new Template();
    t.setRuntimeServices(rs);
    t.setData(sn);
    t.initDocument();

VelocityContext vc = new VelocityContext();
vc.put("username", "John");

StringWriter sw = new StringWriter();
t.merge(vc, sw);

System.out.println(sw.toString());
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top