Total Pageviews

Sunday, April 1, 2012

Using Velocity Templates in Portlets

In the very beginning when I was introduced to Velocity Templates, it was very confusing. But with the passing time, I came to know the importance and now I love to work with them. 
We've used them very often in themes, in fact its an important part of theme.
So story seems quite straight, now lets get a twist. 

What If we want to use them in portlet ???
And in answer, you'll ask me a question why the hell you want do it, if we have JSPs to serve the purpose ?

hmmm !!! You are right... Yea, we have JSPs and they work very well, no doubt... But the thing I'm talking about is related with heavy data rendering and the advantage is - we can process them in action class itself instead of sending them to JSP in response for further processing  for display. We get faster processing, as full rendered HTML is sent to JSP in response. So, in that condition we just need to put that response for output in JSP. Ambigious, huh... trust me, it will be very transparent after you finish this post...

Lets start, do create a portlet, depoy it and add on a page to see default output. Now complex climax of the story begins.
By default, the portlet we create is MVC portlet and use default MVCPortlet class. Now do the following:
1. At First create a custom class and it should inherit com.liferay.util.bridges.mvc.MVCPortlet class.
2. We have to override the doView method where we will write our code for Velocity Engine initialization. This is main task. Lets do it. 
In addition i've written one more function, just for modularization, in which I'm merging velocity template, as under:
3. Now you are done with java. Create a folders inside docroot for keeping templates and JSPs with relevent names. I've created with name VelocityTemplate and HTML respectively. Now create and template in side the VelocityTemplate folder and write some HTML stuff and create your JSP with help of following:
4. Now lets start the writing the climex of the story. We have to edit the portlet.xml and file. We have to change the <portlet-class>, and <init-params> for getting template's and JSP's path, like following:
And trust me, its done... Just try it one or get my attaced war file for referance. Cheers !!!