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")}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With