在for循环中,变量$ dispNames使用用户名和姓更新。
set( $dispNames = $dispNames + $user.firstName + " " + $user.lastName + ", ")
如何检查该用户是否已存在于字符串中并忽略添加到此变量?
这里的好习惯是确保您正在迭代的Java集合中没有重复项,或者通过将这些名称放在Java端的Set中来删除重复项。
但是,如果您的环境中无法访问此解决方案,则可以尝试:
#set ($seenUsers = {})
#foreach ($user in $myUsersCollection)
#set ($fullName = "$user.firstName $user.lastName")
#if (!$seenUsers.containsKey($fullName))
#set ($junk = $seenUsers.put($fullName, 1))
#if ($dispNames.length() > 0)
#set ($dispNames = "$dispNames,")
#end
#set ($dispNames = "$dispNames, $fullName")
#end
#end
此解决方案使用地图来记住是否已经看到特定用户。此外,它避免在姓氏后添加昏迷。
您还会注意到,在Velocity中连接字符串的正确方法是使用现有引用格式化更大的字符串,而不是使用专用于数字添加的+运算符。