Access Liferay Services in Velocity Template

liferay-services-in-velocity


aim

We can access Liferay Services in velocity templates. We have many liferay services which sometimes required to access in velocity files.We know that a theme contains many velocity template files.So it would be great to know how to access those services in these template files. This article explains how to access liferay services in our velocity templates with some easy examples. 


What’s Liferay Service?

Liferay follows service oriented architecture. A liferay service is simply method which can be invoked locally or externally. For example User Service which provides information about users of the portal, Organization Service which provides organization information of the portal and so on. We can have even our custom services also. So for simplicity accessing Liferay services means we are accessing  liferay methods. 

[richfocus title=”serviceLocator“]
serviceLocator object is ready to use in velocity template. We can just think this object is open door to access Liferay services in velocity templates.
[/richfocus]

Example 1: Access Liferay User Service (UserLocalService)

#set($userLocalService = $serviceLocator.findService('com.liferay.portal.service.UserLocalService'))

Note 1: If you want to test the above code then copy the above line into your portal_normal.vm file of the current theme.

Note 2: You can call any method of UserLocalService by using the variable $userLocalService as written in the above code. For example $userLocalService.getUsersCount()

Note 3: Check Liferay source code for all the methods in UserLocalService

UserLocalService

 Example 2: Access Liferay Organization Service (OrganizationLocalService)

#set($organizationLocalService = $serviceLocator.findService('com.liferay.portal.service.OrganizationLocalService'))

 


Note

In this way we can access any liferay service.But what about custom services? I mean services under custom portlet. Will we be able to access custom services as explained in the above example? The answer is No. To access custom services we need to pass context path of the portlet in findService method. 


Example 3: Access Custom Service (its part of custom portlet)

#set($bookService = $serviceLocator.findService("book-portlet", "com.proliferay.sbuilder.service.BookLocalService"))

Note 1 : book-portlet is the custom portlet.
Note 2: The service or portlet must be deployed before using it in the velocity templates.
Note 2: The context path of the portlet is the first parameter.

About The Author

1 thought on “Access Liferay Services in Velocity Template”

  1. Hi! Great article, but I have a problem 🙂 how can I access to my portlet services (build by service builder)?
    Thanks!

Leave a Reply

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

Scroll to Top
%d