suppress list elements that have already been encountered

做~自己de王妃 提交于 2020-01-11 13:07:37

问题


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?


回答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.



来源:https://stackoverflow.com/questions/30387317/suppress-list-elements-that-have-already-been-encountered

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!