
Custom Velocity Variables
Table of Contents [-]
Introduction #
If you ever wanted to create more custom Velocity Variables that would be available for your theme to reference it's as easy as setting an attribute in ServicePreAction.java!
Background #
If you look at the template code inside a typical Liferay theme, you will see many velocity variables being referenced. For example inside of the Classic theme's dock.vm, there is a line of code:
<h2 class="user-greeting"> <span>$user_greeting</span> <h2>
$user_greeting fetches the "Welcome Joe Bloggs" sign you'll see when you log in as test@liferay.com Where did $user_greeting come from? Look inside init.vm, and you'll that it's set here:
#set ($user_greeting = $user.getGreeting())
It gets the User object ($user) and retrieves the 'greeting' (.getGreeting()) from the database. Where is the User object set as a velocity variable? The magic happens inside of VelocityVariables.java:
vc.put("user", themeDisplay.getUser());
'vc' is an instance of VelocityContext, and all we are doing here is getting the user object (themeDisplay.getUser()) and assigning it the key of "user". This translates to the ability to using $user as the User object.
Custom Velocity Variables #
- First see what variables are already available.
- Some commonly used ones that are already available include $user, $company, $layout, and $themeDisplay. You probably don't want to create a new one for getting a user's screen name, because you can just do $user.getScreenName().
- ServicePreAction.java
- You'll want to extend the ServicePreAction class first and reference it in portal-ext.properties:
servlet.service.events.pre=com.liferay.portal.events.ServicePreAction,your.custom.EXTServicePreAction
Inside your extended ServicePreAction class, create a Map object with the key and value of the vm variables you want to insert, and then set that into the attribute under the key WebKeys.VM_VARIABLES.
Finally, the WebKeys.VM_VARIABLES gets picked up in VelocityVariables.java:
// Insert custom vm variables Map vmVariables = (Map)req.getAttribute(WebKeys.VM_VARIABLES); if (vmVariables != null) { Iterator itr = vmVariables.entrySet().iterator(); while (itr.hasNext()) { Map.Entry entry = (Map.Entry)itr.next(); String key = (String)entry.getKey(); Object value = entry.getValue(); if (Validator.isNotNull(key)) { vc.put(key, value); } } }