我有一个包含重复元素的列表,我需要使用velocity。
例如,posts 包含重复元素。
#foreach ($p in $posts)
$p.name //will be unique
#end
我想使用velocity去除重复项,
任何帮助将不胜感激。
这是可能的,根据您的velocity版本,这应该可以工作。比上面的答案更简洁。
#set($uniquePosts = [])
#foreach($post in $posts)
#if( ! $uniquePosts.contains( $post.name ) )
#if( $uniquePosts.add($post.name) ) #end
##note the if above is to trap a "true" return - may not be required
$post.name
#end
#end
#if( ! $uniquePosts.contains($post.name) && $uniquePosts.add($post.name)) #end
- Datz为了证明Velocity是可以实现的,虽然不推荐使用,我想举个例子。
对于那些感兴趣的人,以下是实现方法:
#set($uniquePosts = [])
#foreach($post in $posts)
#set($exists = false)
#foreach($uniquePost in $uniquePosts)
#if($uniquePost.name == $post.name)
#set($exists = true)
#break
#end
#end
#if(!$exists)
#set($added = $uniquePosts.add($post))
#end
#set($posts = $uniquePosts)
#end
Unique list:
#foreach($post in $posts)
$post.name
#end
在Velocity中你不能这样做。你必须提供一个不包含重复元素的模型。最简单的方法是使用new HashSet<Post>(postsList)
- 这将消除重复项(基于equals(..)
方法)
如果你真的无法传递正确的模型,你可以尝试定义一个自定义工具,它接受一个列表并返回一个集合,但这并不容易。
除了Velocity不支持之外,从架构角度来看,你想要的根本没有意义。 "去重"部分是某种逻辑,需要在正确的位置处理。视图不是做这件事的正确地方。因此,您应该尽一切可能在Java中完成它,甚至会很高兴它在Velocity中不可能。
即使您的角色不允许更改Java代码,仍必须在Java中解决此问题。