Reputation: 510
I am using Thymeleaf #lists.contains but cannot get this scenario to work.
I have an ArrayList in Java as such:
List<String> data = new ArrayList<String>();
The list conatins numbers: [1,2,3]. Now in Thymeleaf I want to check if a number is in a list then print my checkbox as checked, I am trying this:
<input type="checkbox" th:if="${#lists.contains(data,1)}" name="checklist" checked="true" />
<input type="checkbox" th:unless="${#lists.contains(data,1)}" name="checklist" />
This does not work. None of the checkboxes are checked. I would have expected for the 1 in the list and the 1 in the if to match and check the checkbox.
For some reason Thymeleaf is not working like this. If I append all the values with something like a c, example ['c1','c2','c3'] and test for that, then it works perfectly. So is it an number/string testing problem and how do I get it to work without appending a character to the number?
If I print the variables out, I get this:
${#lists.contains([1],1)} = false
${#lists.contains([1],'1')} = true
So if I had to use variable on both side, how would I add the quotes? I tried this but it does not work:
${#lists.contains(data,"numvar")}
Upvotes: 3
Views: 11154
Reputation: 4671
to find the value in array, this worked for me:
<input type="checkbox" th:name="plates[]" th:checked="${#arrays.contains(array, 1)} ? 'checked'" th:value="${plate.id}">
Upvotes: 0
Reputation: 20487
If you have an array of Strings, you have to search using a string:
<input type="checkbox" th:if="${#lists.contains(data, '1')}" name="checklist" checked="true" />
Just like the java:
List<String> strings = new ArrayList<>(Arrays.asList("1","2","3"));
System.out.println(strings.contains(1)); // returns false
System.out.println(strings.contains("1")); // returns true
If you have an array of Integers, you have to search using an Integer:
<input type="checkbox" th:if="${#lists.contains(data, 1)}" name="checklist" checked="true" />
Just like the java:
List<Integer> integers = new ArrayList<>(Arrays.asList(1,2,3));
System.out.println(integers.contains(1)); // returns true
System.out.println(integers.contains("1")); // returns false
Upvotes: 2
Reputation: 510
So the way I fixed this was to do this:
${#lists.contains(data, '' + numvar + '')}
Just to recap, the data variable is an ArrayList of Strings. The numvar variable is an int number. To compare the two you have to wrap the numvar around single quotes, and this is how you have to do it. Thanks Metroids for pointing it out.
Upvotes: 1