Liferay: Add methods/constants to Velocity context
In your Velocity templates you may need to access some parts of your API / constants. Here is one simple way to do this (there are other ways).
Here are the steps:
- Create a class that extends com.liferay.portal.kernel.events.Action
- Register this action in portal-hook.properties
- Enjoy!
1. Create a class that extends com.liferay.portal.kernel.events.Action
This class should be put in a Liferay hook. This Action class will be executed by Liferay once your server has started.
In the below code snippet we add to velocity context:
- one Java object (use a singleton if it’s a util class) : instance of MyUtilClass
- one Java const called “MY_CONST” with the value “WORLD”
2. Register this action in portal-hook.properties
Then build & deploy your hook.
Liferay will execute this action in the class MainServlet, check Liferay source code if you want to have a better understanding of the logic.
3. Enjoy!
Now in your velocity templates you can use your Java object and your Java constant:
There are other ways to do it, I think that this one is the most simple one.