Custom variables in velocity and freemarker templates in liferay DXP/7

blog-banner

While developing theme in liferay we can use many common available velocity/freemarker variables like: $processor, $request, $themeDisplay, $company, $user, $realUser, $layout, $layouts, $plid, $layoutTypePortlet, $portletGroupId, $locale, $timeZone, $theme, $colorScheme and $portletDisplay etc. But at some point this common variables can not fulfil our requirement. For that, we may need to use our own custom variable which behaves as per our need.

We can expose our custom variable to templates(For both velocity and freemarker). Here I am going to demonstrate how we can do it for Liferay DXP for both velocity and freemarker template.

Prerequisite: Liferay 7 DXP development and basics of liferay hook.

To expose custom variable for templates in liferay you need to follow the below steps:

Expose custom variable in velocity template:

Here we are exposing custom variable in Velocity template by following steps:

Step 1: Create liferay hook to and register a servlet pre service action with servlet.service.events.pre

Create following class:

public class CustomVaribale extends Action{

	@Override
	public void run(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
	throws ActionException {

		Map< String, Object > customVariables = new HashMap<String, Object>();

		customVariables.put("st_demo1", "surekha");
		customVariables.put("st_demo2", "technologies");

		httpServletRequest.setAttribute( WebKeys.VM_VARIABLES, customVariables);
	}
}

Now add following property into portal.properties

servlet.service.events.pre=com.st.customvalocityvariable.CustomVaribale

Liferay-hook.xml

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

Step 2: Deploy the code.

Step 3: Now the exposed custom variable are ready to use, You can access st_demo1 and st_demo2 presided with $ sign like $st_demo1 and $st_demo2 in template.

Expose custom variable in freemarker template:

In freemarker, Way of accessing custom variable is different than velocity templates.

You can use hook variables as below in freemarker templates:

${st_demo1} 

${st_demo2}
Contact us

For Your Business Requirements

Text to Identify Refresh CAPTCHA
Background Image Close Button

2 - 4 October 2024

Hall: 10, Booth: #B8 Brussels, Belgium