functionmethodsvelocity

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?


Solution

  • Maybe you are looking for a macro ? https://velocity.apache.org/engine/devel/user-guide.html#velocimacros:~:text=)%0A%24block-,Velocimacros,-%C2%B6

    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>