You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@velocity.apache.org by Hiroaki Nakamura <hn...@v003.vaio.ne.jp> on 2002/11/15 23:35:35 UTC

[PATCH] StringResourceLoader

I made a patch to add StringResourceLoader, which can instantiate a template
object from a String containing VTL. A test suite is also included.
StringTemplateTestSuite does the same tests using StringResourceLoader
as TemplateTestSuite. This patch is the diff from 1.3.1-rc2.

This is a quick and dirty implementation. Some characters (',', '\r', '\n', '\\')
are escaped to work around ExtendedProperties parsing and are unescaped
afer parsing. Ugly but it works :)

I know you may use evaluate() instead, but it parses a template every time.
So I think StringResourceLoader is useful when you use the same template
many times. Please tell me what do you think.

Usage example:

// initialization
Properties templateStrings = new Properties();
templateStrings.put("template1", "Hello, $person");
templateStrings.put("template2", "Welcome to $place.");
String resourceLoaderName = "string";
VelocityEngine engine = new VelocityEngine();
engine.init(StringResourceLoader.createInitProperties(resourceLoaderName, templateStrings));

// use template (as usual)
Template template = engine.getTemplate("template1");
VelocityContext context = new VelocityContext();
context.put("person", "John");
StringWriter writer = new StringWriter();
template.merge(context, writer);
writer.close();
String result = writer.toString();

--
)Hiroaki Nakamura) hnakamur@v003.vaio.ne.jp