JavaBlog.fr / Java.lu DEVELOPMENT,Java Java – Apache – Velocity: Simple presentation of Velocity 1/2

Java – Apache – Velocity: Simple presentation of Velocity 1/2

Hello,

In this post, I would expose you another library developped by Apache Foundation: Velocity.

Velocity is a library created by Apache, that allows quick and easy rendering of text pages, more light than the jsp pages. This libray is based on Template, variables, and some utilties classes. Following its success, there are several versions for others platforms like dot.NET.

Below, a simple example with the use of Velocity and templates.

Use of Velocity

public void render(String templatePath, Map<String, Object> context, Writer writer){
	try{
		VelocityContext velocityContext = new VelocityContext(context);
		Template template = Velocity.geTemplate(templatePath);
		template.merge(velocityContext, writer);
	}catch(Exception e){
		throw new RuntimeException("Internal error.", e);
	}
}

Template
Often, the templates are named with the “.vm” extension.
The $variable.method or ${variable.method} expressions are the 2 syntaxes used to display the result of “variable.getMethod()”. “variable” is an entry provided to context. If the result of “variable.getMethod()” is null or unavailable, this initial expression “variable.method” (not replaced) will display in generated final result.

There are also the $!variable.method or $!{variable.method} expressions whose the result is similar than above expressions unless if the result is null then nothing is displayed in place of expression.

The variable $variableTwo has the value “two”:

#set ( variableTwo = "two" )

Here, an example of loop and inlucde of file in the final result without rendering of expressions contained by the included file:

#foreach ($i in $list)
	<tr><th>$i.propertyOne</th><td>$!{i.propertyTwo.propertyNext}</td><td>$i.propertyThree</td><td>$!{i.propertyFour}</td></tr>
#end

#include ("file.txt")

To parse the content of an included file, there is the command #parse like:

#parse ("file.vm")

For more information http://velocity.apache.org/

Kind regards,

Huseyin OZVEREN

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

Related Post