Thymeleaf: Concatenation - Could not parse as expression
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:
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:
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:
Concatenation in attributes with th:attr
For complexity within attributes such as href
or src
, Thymeleaf provides th:attr
to handle concatenation elegantly:
Manage special characters
In case of having special characters in your text, don't forget to escape them like this:
Property value concatenation
For incorporating values from property files, Thymeleaf's #{...}
messages syntax comes in handy:
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:
In these cases, th:attr
or pipe symbols (||
) are the correct options:
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.
Was this article helpful?