Thymeleaf replacing property variable with value from server side

Viewed 387

I am trying to make UI by using Thymeleaf template engine. I have a property file, which contains list of messages for validations.

For example: I have a propery customer.collateral.allocated_amount=Entered amount is bigger than your available balance. Balance: {0}

Now this I wanna replace this {0} with value, which I get from server side from database. For example, I query from database and I get 500.50. And what I want to do now, is to display this propery with value. In this example, it would be: Entered amount is bigger than your available balance. Balance: 500.50

I tried to do this, but no luck:

<th class="right" th:inline="text">([[#customer.collateral.allocated_amount]], ${availableAmount})</th>

How could I do this?

1 Answers

Here are the steps you need to follow for a basic set-up to use Thymeleaf messages:

1) Let's assume you have a Thymeleaf template called customers.html.

2) Your properties file must therefore be called customers.properties, and it must be placed in the same directory as the customers.html template.

3) Let's assume your properties file contains this entry:

amountBiggerThanAvailable=Entered amount is bigger than your available balance. Balance: {0}

4) For the placeholder {0} I will assume you have a Java object called account which has a property called availableAmount and which you pass to Thymeleaf in the usual way (i.e. the same way you pass any other data to your Thymeleaf template). Of course, your version may be different.

Here, I will use a <div> for my example - but you can use whatever you want, of course:

5) Use the message in your template like this:

<div th:text="#{customers.amountBiggerThanAvailable(${account.availableAmount})}"></div>

Note that there is no actual content in the div (between the opening <div> and the closing </div>). All the Thymeleaf directives are attributes inside the opening <div>.

The above fragment will generate the following HTML in your web page:

<div>Entered amount is bigger than your available balance. Balance: 123.45</div>

Once you have got this far, there are various enhancement you can make. For example, you can also look into providing localized (translated) messages as described here.

Related