Thymeleaf: <label> to have dynamic text concatenated with static text Spring MVC

23.7k Views Asked by At

I'm trying to append some text to a dynamic text as shown below:

<label th:text="Hello ${worldText}"></label>

But the UI throws:

TemplateProcessingException: Could not parse as expression: "Hello ${worldText}

Does anyone know how can I achieve this?

3

There are 3 best solutions below

2
On BEST ANSWER

An easy solution would be to insert a span to the label:

<label>Hello <span th:text="${worldText}"></span></label>

But i would prefer to combine text and variables like this:

<label th:text="'Hello' + ${worldText}"></label>
0
On

Some other ways,

// 1. Using the <th:block> element
<label>Hello <th:block th:text="${worldText}"></th:block></label>

// 2. Using string concatenation
<label th:text="${'Hello ' + worldText}"></label>

// 3. Using the pipe (|) character
<label th:text="|Hello ${worldText}|"></label>

// 4. Using expression inlining
<label>Hello [[${worldText}]]</label>

// 5. You could prepare a variable in your controller
// In contoller,
model.addAttribute("helloWorld", "Hello " + worldText);
// In template,
<label th:text="${helloWorld}"></label>

The result will always be,

<label>Hello variable-value</label>
0
On

Another straightforward solution is

<label th:text="${'Hello ' + worldText}"></label>