Question

Being mainly a VB.NET programmer, I am extremely new to VTL (Velocity Template Language). I am currently trying to customise an application that uses Velocity templates and Jython.

I have the following VTL code in an existing file. This code obtains some key-value pairs from a JSON file and outputs them to the browser in a neat table:

<table class="meta">
    #set($keySet = $metadata.getJsonObject().keySet())
    #foreach($key in $keySet)
    <tr>
        <th width="25%">$parent.getFriendlyName($key)</th>
        <td>
            #set($valueList = $metadata.getList($key))
            #if($valueList.size() > 1)
                #foreach($value in $valueList)
                    <span class="meta-value">$self.escape($value)</span><br/>
                #end
            #else
                $self.escape($valueList.get(0))
            #end
        </td>
    </tr>
    #end
</table>

I can display the $keySet array:

[field1, field2, field3, field4]

What I am attempting to do is to sort the strings in the $keySet array in alphabetical order.

I have tried to use the SortTool (http://velocity.apache.org/tools/devel/javadoc/org/apache/velocity/tools/generic/SortTool.html) by changing

#foreach($key in $metadata.getJsonObject().keySet())

to

#foreach($key in $sorter.sort($metadata.getJsonObject().keySet()))

but the array returned by the sort() function is empty.

Also, I did not think that the solution listed in http://www.liferay.com/community/forums/-/message_boards/message/11146823 was applicable as I am not trying to sort on a child field.

Any advice would be greatly appreciated. Thanks in advance.

No correct solution

OTHER TIPS

First thing to check is if you have added SortTool to the velocity context, using code like:

VelocityContext velocityContext = new VelocityContext();
velocityContext.put("sorter", new SortTool());

Having said that, best practice would be to do this kind of work in Java code, not in the template logic. See my answer here for more details and reasons.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top