Friday, December 31, 2010

Velocity Templating and its application in liferay

Velocity is my favorite template language which enables me to get the static pages up in no time with rich content(thanks to the document and image library).
I would like to share some of its fantastic capabilities.
Web content in Liferay is controlled by template scrip file,Velocity can be used for simple transformations in web content/journal portlets which detrmines how the content will be displayed on the page.Velocity can also be utlilized for making custom changes in vm files of Liferay themes.
GUI requirements determine the degree of customization required in VM templates. I have observed cases where a lot of coding effort can be reduced if velocity is used in optimally.

In liferay portal services can also be used with help of velocity in Liferay themes(VM templates)or templates of Articles (web content portlet).
Lifeay provides service locator to use the services with velocity.
TO enable access of services in liferay make following changes in portal-ext.properties
# Input a comma delimited list of variables which are restricted from the
# context in Velocity based Journal templates.
#
journal.template.velocity.restricted.variables=serviceLocator
remove serviceLocator in property it will now look as
journal.template.velocity.restricted.variables=


example --- (a complete example is available in my earlier post named quick tips)
#set ($userLocalService = $serviceLocator.findService("com.liferay.portal.service.UserLocalService"))
#set ($roleLocalService = $serviceLocator.findService("com.liferay.portal.service.RoleLocalService"))

----------------------------------------------------------
Objects that can be used OOB in VM files
$user, $company, $layout, and $themeDisplay
example ---> $user.getFirstName()

themeDisplay,company,user,realUser,layout,layouts,plid,layoutTypePortlet,scopeGroupId,permissionChecker,locale,timeZone,theme,colorScheme,portletDisplay,

other variable you can from VelocityVariables.java class from source code
com.liferay.portal.velocity.VelocityVariables

Check null -- #if ($validator.isNotNull($variable))

Example
Now if you have a page which displays news article for a person with his name and a custom welcome message you can get his name in through web content portlet , template along with his name which can be dropped at top of page so no need to write a java portlet just use velocity
< b > Welcome to news page< /b >
$user.getFirstName()
< tags> news begins

Velocity references
Official documentation
Advanced concepts
Quick Learning
My Favourite reference link