liferayvelocityliferay-velocity

Create object in velocity template


I am writing velocity templates for my liferay theme and I am wondering, whether it is possible to create a new object inside the velocity template.

The reason is that in liferay there is no contextTool registered in the context and I really want to be able to inspect the variables that are present in the template at a given time. There is a cool macro for this, but unfortunately it uses the contexttool.

I'd like to do something like:

#set($contextTool = new ContextTool())

Another solution would be java code that is provided with the liferay theme that is able to add stuff in the template context. But I don't know how this would work either... ;-)


Solution

  • try with

    #set($contextTool = $portal.getClass().forName("full.package.ContextTool").newInstance())
    

    EDIT

    IF I understood you than this should give you what you want

    #set($ve = $serviceLocator.findService("com.liferay.portal.kernel.velocity.VelocityEngine"))
    #set($wvc = $ve.getWrappedStandardToolsContext().getWrappedVelocityContext())
    
    #set($cVE = $portal.getClass().forName("org.apache.velocity.app.VelocityEngine"))
    #set($cHSREQ = $portal.getClass().forName("javax.servlet.http.HttpServletRequest"))
    #set($cHSRES = $portal.getClass().forName("javax.servlet.http.HttpServletResponse"))
    #set($cSC = $portal.getClass().forName("javax.servlet.ServletContext"))
    #set($cCC = $portal.getClass().forName("org.apache.velocity.tools.view.context.ChainedContext"))
    #set($cVEI = $portal.getClass().forName("com.liferay.portal.velocity.VelocityEngineImpl"))
    #set($cC = $portal.getClass().forName("org.apache.velocity.context.Context"))
    #set($cVEU = $portal.getClass().forName("com.liferay.portal.kernel.velocity.VelocityEngineUtil"))
    
    #set($ve = $cVEU.getMethod("getVelocityEngine").invoke(null))
    
    #set($fVE = $cVEI.getDeclaredField("_velocityEngine"))
    $fVE.setAccessible(true)
    
    #set($cc = $cCC.getConstructor($cC, $cVE, $cHSREQ, $cHSRES, $cSC).newInstance($wvc, $fVE.get($ve), $request, $response, $request.getSession().getServletContext()))
    
    #set($contextTool = $portal.getClass().forName("org.apache.velocity.tools.view.tools.ContextTool").newInstance())
    
    $contextTool.init($cc)
    

    After that you can use, for example

    $contextTool.getKeys()
    

    If this is not what you need, let me know ...