Custom Viewtool Example - Documentation topics on: creating custom velocity tools,plugins,taglib,taglibs,viewtool,.

Custom Viewtool Example

Viewtools are simple, they just map a key in Velocity to a class in Java. In this way, they expose/provide a handle to that Java class in Velocity. Viewtools provide the easiest way to extend Velocity using Java code. A Viewtool class implementes the org.apache.velocity.tools.view.tools.ViewTool interface, and provides methods that can be called via Velocity. These methods can return other java Objects, Lists, Strings, or Custom pojos that can be called in your template. Here is a simple example of a Viewool java class:

package com.dotmarketing.plugins.hello.world;

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

public class HelloViewTool implements ViewTool {
  
  public String getHello() {
    return "Hello World Viewtool";
  }

  public String getHello(String myName) {
    return "Hello " + myName ;
  }

    public void init(Object obj) {
    
    }
}

In order to use you new viewtool from Velocity, you must register in the WEB-INF/toolbox.xml file.

<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
which would print out "Hello World Viewtool" or like this:
$helloWorld.getHello("dotCMS")
which would print out "Hello dotCMS".

Keep in mind that Viewtools return java Objects, which can be interacted with in Velocity. For example, if we just wanted to say "Hello", we could call:

$helloWorld.getHello().substring(0,5)

which would call the substring method of the String Object and print out "Hello".

When customizing dotCMS, keep in mind that all this work can and should be done via plugins. See the section on "Development" for more information on the dotCMS plugin architecture.