Explain Codes LogoExplain Codes Logo

Thymeleaf: Concatenation - Could not parse as expression

html
prompt-engineering
thymeleaf-syntax
concatenation
Nikita BarsukovbyNikita Barsukov·Dec 10, 2024
TLDR

To concatenate in Thymeleaf, use the + operator within ${...} construct. For instance, if you were to integrate the variable firstName with the string ' Doe', you would do it as such:

<span th:text="${firstName + ' Doe'}">John Doe</span>

This is one of the main methods for combining dynamic and static content within the th:text attribute.

Merging static and dynamic content

When you need to concatenate static text and dynamic content, you need to wrap the static parts around single quotes. Here's how you do it:

<h1 th:text="${'Hola, ' + user.name + '!'}">// 'user.name' has a new fan!</h1>

Where 'Hola, ' and '!' are the static parts, and user.name is the dynamic part.

Diverse concatenation techniques

Concatenation using pipe (||)

Thymeleaf also offers the || operator, which is often used to make concatenated expressions more readable:

<p th:text="|Hey there, ${user.firstName} ${user.lastName}!|">// Who knew Thymeleaf could be friendly?</p>

Concatenation in attributes with th:attr

For complexity within attributes such as href or src, Thymeleaf provides th:attr to handle concatenation elegantly:

<a th:href="@{|/user/profile/${userId}|}">// Now your profile link too feels dynamic!</a>

Manage special characters

In case of having special characters in your text, don't forget to escape them like this:

<a th:text="${'Click here to view the &quot;Unicorn&quot; page'}">// It's not a myth, it's a page! 🦄</a>

Property value concatenation

For incorporating values from property files, Thymeleaf's #{...} messages syntax comes in handy:

<title th:text="#{home.title} + ' - ' + #{site.name}">My Home - MySite</title>

Cautious Coding Tips

Beware of the IDE warnings

At times, pipe symbols (||) for concatenation can trigger IDE warnings. To avoid these, consider sticking to the good old + operator for concatenation.

Syntax quirks

The concatenation operator cannot be used for concatenating text within attribute values directly. This won't work:

<!-- Warning: Does not compute! --> <img th:src="'/img/' + ${imageName} + '.png'" />

In these cases, th:attr or pipe symbols (||) are the correct options:

<!-- A picture is worth a thousand concatenations --> <img th:src="@{|/img/${imageName}.png|}" />

Quick Hacks

Keep an eye on the docs

Regularly enhancing your knowledge through the official Thymeleaf documentation and community can keep you updated with latest practices.

Bugs or features?

Always test your implementations with different data and ensure your code aligns with Thymeleaf's syntax rules.

Your network is your net worth. Or was it neuron?

Engage with the Thymeleaf community on GitHub to resolve complex problems and share your gems with others.