Table of Contents

Java - Thymeleaf Template Engine

About

Thymeleaf is a Java template engine where the template conforms to the targeted content type.

ie:

Syntax

Construct Description
... evaluate the variable (on the global scope, not in a loop)
#{…} evaluate a message for the given language Ref
*{…} evaluate the variable on the selected object (in a loop) Ref
@{…} link URL
Link Language
Text template TEXT, JAVASCRIPT and CSS
Markup Template HTML and XML

Snippet

Internationalization

when the internationalization message are set setTemplateEngineMessageSource using the greeting message

greeting=Hello, {0} (in no specific language)!
[( #{greeting(${name})} )]

if

[# th:if="${name.length() gt 10}"]Wow! You've got a long name (more than 10 chars)![/]
<td th:text="${user?.address?.city}"></td>
<!-- A null value is evaluated to false -->
<td th:text="${not user}"></td>
<!-- With equality -->
<div th:if="${user.isAdmin()} == false"> 
<!-- null literal -->
<div th:if="${variable.something} == null"> 

Logical

Date

Send Date [( ${#dates.format(sendDate)} )].
<p th:text="${#dates.format(next.Date, 'dd-MMM-yyyy')}"></p>

1)

<a 
    th:href="@{mailto:{to}(to=${nextTouche.email})}" 
    th:if="${nextTouche.email != null}"
    th:text="${nextTouche.name}">
    Name To Contact
</a>

Loop

Called Iteration in the documentation.

Your hobbies are:
[# th:each="hobby : ${hobbies}"]
 - [( ${hobby} )]
[/]
<tr th:each="prod : ${prods}">
	<td th:text="${prod.name}">Onions</td>
	<td th:text="${prod.price}">2.41</td>
	<td th:text="${prod.inStock}? #{true} : #{false}">yes</td>
</tr>

Language

Javascript

The inline Script element can be defined as a text template with the data-th-inline attribute. Ref

The block may be escaped or not

Example with Json

<script data-th-inline="javascript" data-th-if="${goToAction != null}" type="application/ld+json">
{
  "@context": "http://schema.org",
  "@type": "EmailMessage",
  "potentialAction": {
    "@type": "ViewAction",
    "url": "[(${goToAction.url})]",
    "name": "[(${goToAction.name}]]"
  },
  "description": "[(${goToAction.description})]"
}
</script>

Inline Css

<span data-th-style="'background-color:${primaryColor};border-color:${primaryColor}'"></span>
<!-- To append without overwritting -->
<span data-th-styleappend="'background-color:${primaryColor};border-color:${primaryColor}'"></span>