liam beck
liam beck

Reputation: 77

pass thymeleaf variable as parameter in method

I concatenate the state and my stateCounter to one String. This is my value for my HashMap which stores all the States but I don't get it to to put this variable in my method.

<span th:with="stateName=${item.state} + ${item.stateCounter}"></span>
<td th:text="${{order.getStateRepository().get(${stateName})}}"></td>

Upvotes: 1

Views: 3453

Answers (2)

andrewJames
andrewJames

Reputation: 21910

Some notes:

(1) Using a <td> tag suggests you are also using a <table>. Having a <span> tag next to a <td> tag inside a table is not valid HTML (assuming this is what it looks like in your template - maybe this is just a copy/paste thing).

(2) If your order object has a stateRepository field, then you don't need to use a getter order.getStateRepository(). You can just use the field name order.stateRepository. You are already doing this with item.state, for example. Thymeleaf will figure out from the field name how to use the related getter - e.g. item.getState().

(3) The scope (availability/visibility) of a local variable, such as stateName in th:with="stateName=${item.state} is limited to the tag in which it is declared, and also to any sub-tags. You do not have any sub-tags in your <span> - therefore the variable is not visible anywhere outside of your span. So, it is not available inside the <td> tag.

(4) Do you need to use a local variable in your example?

Instead of using get(stateName), you can use the expression referred to by stateName directly:

get(item.state + item.stateCounter)

So overall, this should work (based on the assumptions above):

<td th:text="${order.stateRepository.get(item.state + item.stateCounter)}"></td>

Maybe you do need the local variable, of course. It may depend on the wider context of the Thymeleaf template.

Upvotes: 2

İsmail Y.
İsmail Y.

Reputation: 3945

You are trying to use local variable. It will work if you try as follows:

<div th:with="stateName=${item.state} + ${item.stateCounter}">
    <td th:text="${order.getStateRepository().get(stateName)}"></td>
</div>

Upvotes: 0

Related Questions