Getting started with Velocity templating engine: Constructing HTML content in a Spring-based Java application


1. Create a velocity template file – say, helloworld.vm, and add this to classpath. Add some html content.

<html>
<body>
<h1>Hello World!</h1>
</body>
</html>

2. If I want to make ‘Hello World’ part dynamic, here’s what you need to do.


<html>
<body>
<h1>${helloContent}</h1>
</body>
</html>

3. Now, to ask Velocity engine to replace the helloContent dynamically,

i) construct a map and add a key ‘helloContent’ and a value.


Map model = new HashMap();
model.put("helloContent", "Hello Velocity!);

ii) Invoke Velocity Engine and get the constructed HTML text


String emailContent = VelocityEngineUtils.mergeTemplateIntoString( velocityEngine, "helloworld.vm", model);

iii) velocityEngine is something we need to inject through Spring IoC (bean context).


<bean id="velocityEngine">
<property name="velocityProperties">
<value>
resource.loader=class
class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader
</value>
</property>
</bean>

4. You’ll get the resultant HTML content in emailContent variable which you use for emails/displaying web pages.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 27 other followers

%d bloggers like this: