0

Hi I have a velocity template that I am trying to edit

it currently has a block that looks like

#foreach( $element in $myList )
  $element.field1 ($element.field2) issued by $element.field ($element.field4 )
<br><br>
#end

the problem is some elements in the list are duplicated and I need to suppress the duplicates.

psuedo code for what I want is

for each element in list
    if element is not in displayed
        display element
        add element to displayed
    endif
endfor

can someone point me in the right direction?

BevynQ
  • 8,089
  • 4
  • 25
  • 37

1 Answers1

1

This kind of logic (de-duplication) is probably something to be avoided in your view (Velocity) layer. Following Model-View-Controller, it would be better to have this logic managed by controller classes, leaving the Velocity template to simply render the data structure it is passed.

For example, by using a data structure such as a java.util.Set, duplicates would not be admitted and so there would be no need for the template to de-duplicate.

Personally I found Rob Harrop's Pro Jakarta Velocity a really good guide to MVC, especially Chapter 4 "Using Velocity in an MVC environment".

Have the model use a Set, have your controller code populate the set, and then the simple loop in your template code can be used as it is now.

In general, the less logic you implement in your view layer, the better. It will also make your code easier to test, so you can verify its behaviour without having to fire up the presentation components, app servers etc etc.

If there really is no choice and the logic absolutely must be written in the template, then the following implements the psuedocode presented:

#set($displayed = [])
#foreach( $element in $myList )
  #if(!$displayed.contains($element))
    $element.field1 ($element.field2) issued by $element.field ($element.field4 )
    <br><br>
    #set($ignore = $displayed.add($element))
  #end
#end

Note the messiness with #set($ignore = $displayed.add($element)) - this has to be done to suppress the output from java.util.List's add() method (boolean) from being output. Another reason not to write this in template code!

Of course, you would also need to make sure that equals() is correctly implemented on the type added to the list so that the List operations - contains() and add() work correctly.

Definitely an inferior solution to the MVC approach above, but presented as an option of last resort.

Stephen Hartley
  • 945
  • 1
  • 11
  • 17