Custom Velocity Variables

Aim of this article: Add custom velocity by hook.

Use of Custom Velocity Variables:  We will be able to use custom velocity variable directly in the VM files.It  separates  java logic from VM file. Code looks better.  

While developing Liferay theme we have used many velocity variables. Some of the common velocity variables widely used in theme are


$processor
$request
$themeDisplay
$company
$user
$realUser
$layout
$layouts
$plid
$layoutTypePortlet
$portletGroupId
$locale
$timeZone
$theme
$colorScheme
$portletDisplay

We know that sometimes we need more than default. Liferay is flexible to add our own custom velocity variables. Below are the step by step guide

Step 1:

Create a hook  to override servlet.service.events.pre of portal.properties. In this article I am not going to discuss how to create hook. But all these information will be enough to create the hook. You can use Liferay IDE to create the hook. In my eclipse the project look like as below

Custom Velocity Variables
Custom Velocity Variables

CustomVelocityDemo


package com.proliferay.demo;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.liferay.portal.kernel.events.Action;
import com.liferay.portal.kernel.events.ActionException;
import com.liferay.portal.kernel.util.WebKeys;
/**
*
* @author Hamidul Islam
*
*/
public class CustomVelocityDemo extends Action{

@Override
public void run(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
throws ActionException {
/**
* Create and empty map
*/
Map< String, Object > customVelocityVariables = new HashMap<String, Object>();

/**
* For demo we are creating here two velocity variables. One is variable1
* another is variable2
*/
customVelocityVariables.put("variable1", "This is the first variable");
customVelocityVariables.put("variable2", "This is the second variable");

/**
* Keep the customVelocityVariables map in request scope
*
*  WebKeys.VM_VARIABLES should be the attribute name
*
*  For example in VM put $variable1 you will get the corresponding value
*/
httpServletRequest.setAttribute( WebKeys.VM_VARIABLES, customVelocityVariables );
}

}

portal.properties


servlet.service.events.pre=com.proliferay.demo.CustomVelocityDemo

liferay-hook.xml


<?xml version="1.0"?>
<!DOCTYPE hook PUBLIC "-//Liferay//DTD Hook 6.2.0//EN" "http://www.liferay.com/dtd/liferay-hook_6_2_0.dtd">

<hook>
<portal-properties>portal.properties</portal-properties>
</hook>

 

Step 2:

Deploy the hook

 

Step 3:

Use the velocity variable in VM file in your theme like $variable1

I have not explained the code. Instead I have added necessary comment. Read those comments for better understanding.

Download Source Code

About The Author

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top
%d