Search code examples
javaspringthymeleaf

Replace text from controller and put it inside property file


Replace text from controller and put it inside property file

What I have already:

My controller:

redirectAttrs.addFlashAttribute("userName", "Hello, " + someForm.getName() + " nice to meet you.");

My thymeleaf

<p class="text-danger" th:text="${userName}">userName</p>

I know that I can easly use my properties like this:

My message.properties:

user.name=Tom

My thymeleaf:

<a th:text="#{user.name}"></a>

But can I reach what I want if there is a value inside?

My user.name=Hello, {name} nice to meet you.

I would like probably do something like this:

in my controller just:

redirectAttrs.addFlashAttribute("userName", someForm.getName());

and in my thymeleaf:

<a th:text="#{user.name(name=${userName})}"></a>

Is that even possible? How finally should thymeleaf looks like in case like this?


Solution

  • Change your property value like following:

    user.name=Hello, {0} nice to meet you. 
    

    And then pass userName like below:

    <a th:text="#{user.name(${userName})}"></a>
    

    The rule is you can add add multiple variables in your property using{0}, {1}, {2}, .... {n}. And you can pass values like th:text="#{user.name(${param0},${param1},${param2}, ..., ${paramN} )}"