Java - Thymeleaf Template Engine

1 - 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

3 - 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

4 - Snippet

4.1 - 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})} )]

4.2 - 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"> 

4.3 - Date

  • date format (Text template)

Send Date [( ${#dates.format(sendDate)} )].

4.4 - 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>

5 - Language

5.1 - 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>

5.2 - Inline Css


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


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap