Java - Thymeleaf Template Engine

About

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

ie:

  • If the document created is an HTML document, the template is HTML conform
  • If the document created is an Javascript document, the template is Javascript conform

Syntax

  • Quick Construct
Construct Description
${…} evaluate the variable on the global scope
#{…} evaluate a message for the given language Ref
*{…} evaluate the variable on the select object (in a loop) Ref
@{…} link URL
  • Type of language
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)!
  • In a text template,
[( #{greeting(${name})} )]

if

  • If greater than in Text template
[# th:if="${name.length() gt 10}"]Wow! You've got a long name (more than 10 chars)![/]
  • if not null in html template
<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"> 

Date

  • date format (Text template)
Send Date [( ${#dates.format(sendDate)} )].

Loop

Called Iteration in the documentation.

  • In a text template
Your hobbies are:
[# th:each="hobby : ${hobbies}"]
 - [( ${hobby} )]
[/]
  • In a markup template
<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

  • not escaped: [(${variable})] outputs variableValue
  • escaped: [[${variable}]] outputs “variableValue”

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

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

Powered by ComboStrap