Search code examples
htmljsonthymeleaf

Evaluate a variable inside a variable with thymeleaf


I am receiving bin data as json. The number of bins in each section is different, but for instance it might be:

var jsonmsg={"1": "SIXTY", "2": "DISCONNECTED", "3": "TWENTY", "4": "FULL", "5": "TEN"});

I already know the number of bins in each section so bins=5 is known

So I am trying to pass the bin number and json values as class eg: class="bin3 TWENTY"

This is my thymeleaf code

<th:block th:each="i : ${#numbers.sequence( 1, bins, 1)}">
    <div class="grid-item">something else</div>
    <div class="grid-item">something else</div>
    <div class="grid-item"><div th:class="bin+${i}" th:classappend="${jsonmsg.[[${i}]]}"></div></div>
</th:block>

class="bin3" works fine, but I can't work out how to request jsonmsg.* correctly. I have also tried without [[]].

I have also tried:

th:classappend="${jsonmsg[i]}"

I always get the message:

Exception evaluating SpringEL expression


Solution

  • Sorry I think this premise is flawed.

    1. I am trying to manipulate a server side process with client side data. The server side rendering is already complete by then so instead I need client side data to be processed client side with javascript, (not thymeleaf). So I will use javascipt classList.add to update classes as required.

    2. I should be iterating though the jsonmsg directly, not using integers.

    I will leave this flawed question as is, in case anyone else tries to use client side data (like stomp) to manipulate Thymeleaf templates.