Using custom services or liferay services in liferay themes (velocity templates)?

前端 未结 2 1946
心在旅途
心在旅途 2021-01-06 15:31

How to use custom services method in liferay themes in velocity files like init_custom.vm, portal_normal.vm etc.

I see liferay provides a l

2条回答
  •  不思量自难忘°
    2021-01-06 15:53

    You can extend velocity context used in theme with custom variables and services using following hook plugin. Let's say you need to use your custom local service.

    1. create a hook plugin with following liferay-hook.xml definition

      
          portal.properties
      
      
    2. create portal.properties in main/resources (when you use maven) or in docroot/WEB-INF/src (when you use plugins sdk), place following configuration there

      servlet.service.events.pre=com.my.custom.action.MyCustomPreAction
      
    3. create com.my.custom.action.MyCustomPreAction class in your hook that will extend com.liferay.portal.kernel.events.Action

    4. implement run method

      @Override
      public void run(final HttpServletRequest request, final HttpServletResponse response)
          throws ActionException {
      
          Map vmVariables = (Map) request.getAttribute(WebKeys.VM_VARIABLES);
          if (vmVariables == null) {
            vmVariables = new HashMap(1);
          }
          vmVariables.put("myCustomServiceUtil", com.my.custom.service.MyCustomLocalServiceUtil.class);
          request.setAttribute(WebKeys.VM_VARIABLES, map);
      }
      
    5. after your hook is deployed you can use your custom service in velocity template of your theme

      // this code calls method from MyCustomLocalServiceImpl class to fetch items
      #set ($listOfItems = $myCustomServiceUtil.getAllItems())
      

提交回复
热议问题