Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache Velocity: How to define a custom method like in Java?

I currently compose a wiki page in the Polarion Application ALM Software and the syntax on these pages includes (as far as I know) HTML, Javascript and Apache Velocity.

So I wanted to write a script in Apache Velocity because I thought it is the best way to access the Polarion Work Items since there are predefined methods.

Now I want to write a method which iterates through a bunch of workitems and collects their ids in a list or array.

So I just wanted to define a new method like in Java (http://www.tutorialspoint.com/java/java_methods.htm) but I cannot find anywhere on the web how this is done in Velocity (I also searched for "functions Apache Velocity" also with no result).

Is this even possible or do I have to use Javascript if I i want to write my own methods/functions?

like image 711
Bruder Lustig Avatar asked Feb 10 '23 00:02

Bruder Lustig


2 Answers

This can be done, create a static class with the method you want to use in velocity template. Set this class in velocity context object.

velocityContext.put("anyKey",YourStaticClass.class)

This class will be available in velocity template. You can then access its methods like: anyKey.Method()

like image 79
ashish Avatar answered Feb 23 '23 08:02

ashish


Maybe you are looking for a macro ? http://people.apache.org/~henning/velocity/html/ch07.html

Snippet from the above link:

Here is a Velocimacro that takes two arguments, a color and a list of objects:

#macro( tablerows $color $values )
  #foreach( $value in $values )
    <tr><td bgcolor=$color>$value</td></tr>
  #end
#end

#set( $greatlakes = ["Superior","Michigan","Huron","Erie","Ontario"] )
#set( $color = "blue" )

<table>
  #tablerows( $color $greatlakes )
</table>

The tablerows macro takes exactly two arguments. The first argument takes the place of $color, and the second argument takes the place of $values. Anything that can be put into a VTL template can go into the body of a Velocimacro.

Notice that $greatlakes takes the place of $values. When this template is rendered, the following output is generated:

<table>
<tr><td bgcolor="blue">Superior</td></tr>
<tr><td bgcolor="blue">Michigan</td></tr>
<tr><td bgcolor="blue">Huron</td></tr>
<tr><td bgcolor="blue">Erie</td></tr>
<tr><td bgcolor="blue">Ontario</td></tr>
</table>
like image 39
Vincent Gerris Avatar answered Feb 23 '23 08:02

Vincent Gerris