Documentation for the worlds leading Java Based Open Source Web Content Management System

dotCMS

Custom Velocity Tools

Custom Velocity Tools (Viewtools) provide the easiest way to extend velocity using Java code. Using Java code allows much more freedom in extending dotCMS than by just using Velocity code. A Viewtool is simply a Java class that implementes the Viewtool interface, and provides methods that can be called. These methods return strings that merged into your template. For example:

package com.dotmarketing.plugins.hello.world;

import org.apache.velocity.tools.view.tools.ViewTool;

public class HelloViewTool implements ViewTool {
  
  public String hello() {
    return "Hello World viewtool";
  }


    public void init(Object obj) {
    
    }
}

In order to use you new viewtool from Velocity, you must register in the toolbox. This can be done by declaring it in the conf/toolbox-ext.xml file in you plugin:

<tool>
  <key>helloWorld</key>
  <scope>application</scope>
  <class>com.dotmarketing.plugins.hello.world.HelloViewTool</class>
</tool>

Once declared, you can call your new viewtool in the same way as you call all other viewtools that come with the system:

$helloWorld.hello()

For access to the request on a viewtool you must set the scope on your tool within the tool box to be request. This allows you access to the request. You can get it within the init method of your tool. By default unless you need it you should make your tool keep the scope of application. You can also use session as a scope. Look at the following code for an example of not only how to get at the request but to pull the user from the request.

  private HttpServletRequest request;
  private Context ctx;
  private User user = null;
  private User backuser = null;
  private UserWebAPI userAPI;

  // private HttpServletRequest request;
  public void init(Object obj) {
    ViewContext context = (ViewContext) obj;
    this.request = context.getRequest();
    userAPI = WebAPILocator.getUserWebAPI();
    try {
      user = userAPI.getLoggedInFrontendUser(request);
      backuser = userAPI.getLoggedInUser(request);
    } catch (Exception e) {
      Logger.error(this, "Error finding the logged in user", e);
    }
  }
2

Subscribe to dotcms

Visit this group