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

3

13

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?

Harrisharrisburg answered 8/9, 2017 at 14:38 Comment(0)
N
34

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>
Neck answered 8/9, 2017 at 14:41 Comment(2)
Worked for me. Former seems like a work around, but latter suites well in my case, I have some more things to append in the text. Thanks :)Harrisharrisburg
Seems text is not an official attribute for <label>, therefore your first approach is betterWrac
C
3

Another straightforward solution is

<label th:text="${'Hello ' + worldText}"></label>
Cowgirl answered 28/2, 2020 at 10:16 Comment(0)
F
1

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>
Fluidextract answered 18/12, 2022 at 0:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.