How to check if value exists in an array using Velocity Template Language
Asked Answered
M

1

9

I am not sure how I could achieve the following using Velocity Template Language.

Essentially, I'd like to check if a given value exists from the given list/array. In C#, it's equivalent to .Any() or .Contains() method.

#set($myValues = ["apple", "banana", "strawberry"])
#foreach($i in $items)
    $myValues.any($i) <= better way to achieve this??
    or something like this
    $myValues.contains($i)
#end

Of course, I could just use multiple if...else... conditions and loop through the list to check the existence of a certain value, but the code gets messy very quickly (if a lookup list is huge). Is there any better way to do this?

Maidel answered 22/8, 2019 at 7:34 Comment(1)
$myValues.contains($i) should work just fine as velocity can interpret such method calls, as long as they are javaQueridas
C
13
$myValues.contains($i)

or

$list.contains($myValues, $i)

(this one is deprecated since the former was introduced in Velocity 1.6)

Congruity answered 22/8, 2019 at 7:41 Comment(2)
Thanks Andrew. Would it be case-sensitive?Maidel
@Maidel yes, "A" and "a" isn't the same in Java if you use String's equals (which will be used by List#contains)Congruity

© 2022 - 2024 — McMap. All rights reserved.