Hurry! 20% Off Ends SoonRegister Now

Thymeleaf Tutorial - What is Thymeleaf

Do you want to learn how to create a stylish and well-formed way of creating templates? Here is all the information you need to learn about the Thymeleaf tutorial. We will discuss the type of templates thymeleaf is capable of processing. Also, we will see the implementation with the help of the Spring Boot Thymeleaf example. 

Thymeleaf's main goal is to make creating templates elegant and easy to keep up-to-date. To do this, it builds on the idea of Natural Templates to add its logic to template files in a way that doesn't stop the template from being used as a design prototype. This makes it easier for design teams to talk to development teams and bridges the gap between them.

Thymeleaf was also made from the start with Web Standards, especially HTML5, in mind. This means that you can make fully validating templates if you need to. So get into detail to know more about this Thymeleaf tutorial.

Table of Contents: Thymeleaf Tutorial

What is Thymeleaf?

The Apache License 2.0 governs the use of the open-source Thymeleaf Java library. It's a template engine for HTML5, XHTML, and XML. It is a servlet-based server-side Java template engine that may be used in both web-based and offline (offline) settings. For current HTML5 JVM web development, it is ideal. It provides full integration with the Spring Framework.

To display data or text generated by the programme, a set of transformations are applied to template files. It can be used to serve XHTML and HTML5 in web applications.

Thymeleaf's objective is to offer a stylish and organized way to make templates. It is founded on the tags and properties of XML. Instead of directly expressing that logic as code inside the template, these XML tags indicate how preset logic will be executed on the DOM (Document Object Model). It serves as a JSP replacement.

The Thymeleaf architecture enables the quick processing of templates that rely on the caching of parsed files. The smallest number of I/O operations are used during execution.

What is Thymeleaf
If you want to enrich your career and become a professional in Core Java, then enroll in "Core Java Training". This course will help you to achieve excellence in this domain.

Why do we use Thymeleaf?

HTML and JSP are somewhat similar. But unlike Thymeleaf, it is not entirely HTML-compatible. Unlike a JSP file, a Thymeleaf template file can be opened and shown properly in a browser.

As with Spring EL, Thymeleaf supports variable expressions (${...}), which are executed on model attributes. Asterisk expressions (*{...}), which are used for hash expressions (#{...}), which are used for internationalization, form backing beans, and link expressions  (@{...}), which rewrite URLs, are also supported.

Thymeleaf is effective for Rich HTML emails, much like JSP is.

Why do we use Thymeleaf
Related Article: Thymeleaf vs JSP

What types of Templates is Thymeleaf Capable of Processing?

The six categories of templates that Thymeleaf can handle are as follows (also known as Template Mode):

  • Valid XML
  • XML
  • XHTML
  • Valid XHTML
  • Legacy HTML5
  • HTML5

All of the modes mentioned above, excluding the Legacy HTML5 option, make reference to clearly defined XML files. It enables us to process HTML5 files that contain features like independent tags, tag attributes without values, or text that is not enclosed in quotation marks.

Thymeleaf conducts a transformation to transform files into an XML file with the proper structure in order to handle files in this particular mode (valid HTML5 file).

Additionally, Thymeleaf lets us design our own mode by defining a method for parsing templates in this mode. In this method, Thymeleaf could effectively parse anything that can be represented as a DOM tree as a template.

Related Article: HTML vs XML

The Standard Dialect

We can specify DOM nodes using the Thymeleaf template engine framework. the parsed DOM nodes by the templates.

Processor is the name of an object that imparts logic to a DOM node. The dialect is a collection of processors and some extra artifacts. The Standard Dialect is the dialect of the core library of the Thymeleaf.

We can construct our own languages if we want to define our own processing logic while utilizing the library's sophisticated capabilities. We can configure multiple dialects simultaneously in a template engine.

The Thymeleaf integration packages specify the SpringStandard Dialect as a dialect (thymeleaf-spring4 and thymeleaf-spring3). Nearly identical are Standard Dialect and SpringStandard. However, a few minor adjustments in the Standard Dialect allow for improved utilization of some Spring Framework functionalities.

Use Spring Expression Language as an example rather than Thymeleaf's default ONGL (Object-Graph Navigation Language).

Any kind of template processing is supported by Standard Dialect. However, it is ideal for web-based template styles (HTML5 and XHTML). It adheres to and is validated by the subsequent XHTML specifications:

  • XHTML 1.0 Frameset
  • XHTML 1.0 Transitional
  • XHTML 1.1.
  • XHTML 1.0 Strict

Browsers may see HTML5/XHTML template files without processing them thanks to the attribute processor known as the Standard Dialect processor. They disregard the other features, which is why.

For instance, when a JSP file uses a tag library, it contains a section of code that a browser cannot show, such as:

<form:inputText name="student.Name" value="${student.name}" />

The following code enables us to accomplish the same job using the Thymeleaf Standard Dialect.

<input type="text" name="student name" value="Thomas" th:value="${student.name}" />

We can also define a value attribute in the code shown above (Thomas). When the prototype is opened in the browser, the value will be shown. The value from the evaluation of ${student.name} during the Thymeleaf processing of the template will be used to replace the attribute.

It reduces the effort needed to convert a static prototype into a functional template file by enabling a designer and developer to work on the same template file. It's called "Natural Templating."

MindMajix Youtube Channel

Thymeleaf Features

  • Both web and non-web environments are compatible with it.
  • HTML5/XML/XHTML template engine for Java.
  • I/O is minimized by its high-performance parsed template cache.
  • If necessary, it can serve as a framework for a template engine.
  • It supports XML, XHTML, and HTML5 as well as other template formats.
  • Developers can expand upon it and produce original dialects.
  • Its foundation is a set of modular characteristics known as dialects.
  • It encourages globalization.

Thymeleaf Implementation

By including a dependency for spring-boot-starter-thyme leaf in the pom.xml file for our application, we can implement the Thymeleaf template engine. The template engine is set up by Spring Boot to read templates from the /resource/templates directory.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Spring Boot Thymeleaf Example

Let's implement the Thymeleaf template and develop a Spring Boot application.

Step 1: Open Spring Initializr at http://start.spring.io in the first step.

Step 2: Pick the Spring Boot 2.3.0.M1 version.

Step 3: Give the name of the group. Com.javatpoint is available.

Step 4: Provide the Artifact Id in Step 3. Spring-boot-thyme-leaf-view-example is what we've supplied.

Step 5: Include the Spring Web and Thymeleaf dependencies.

Step 6: Press the Generate button. The requirements are packaged in a Jar file and downloaded to the local system when we click the Generate button.

Thymeleaf Example

Step 7: Paste the Jar file into the STS workspace after extracting it.

Step 8: STS should import the project folder.

File -> Import -> Existing Maven Projects -> Browse -> Select the folder spring-boot-thymeleaf-view-example -> Finish 

Importing takes some time.

Step 9: Make a model class and place it in the com.javatpoint package. A model class called User has been generated.

We have created Getters and Setters for the two variables name and email that we have defined in this class.

User.java

java

Step 10: a controller class should be made. A controller class called DemoController has been developed.

DemoController.java

DemoController.java

The Thymeleaf templates will be made in the next stage.

Step 11: Create a Thymeleaf template called user-data inside the project's templates (src/main/resources/templates) folder.

New -> Other -> HTML File -> Next -> Right-click the templates folder. Name the file, then press "Complete"

<html lang="en" xmlns:th="http://www.thymeleaf.org">

User-data.html

User-data.html

Step 12: Create an HTML file in the templates folder in a similar manner. We have made an HTML document called index.

Index.html

Index.html

Step 13: Add the following properties by opening the application.properties file.

Application.properties

Application.properties

The project directory looks like this once all the files, folders, and packages have been created:

packages have been created

Run the application now.

Step 14: Launch the Java application by opening the SpringBootThymeleafViewExampleApplication.java file.

ThymeleafViewExampleApplication.java file

Step 15: Open a browser now and type http://localhost:8080 into the address bar. It displays the results, as displayed below.

 browser 1

Enter your user name and email address, then press the "Submit" button.

"Submit" button.

The user data is displayed after pressing the Submit button at http://localhost:8080/save, as illustrated below.

user-data is displayed
Related Article: Spring Tutorial

Thymeleaf FAQ’s

1. What is Thymeleaf used for?

Thymeleaf is a Java-based server-side template engine that can process HTML, XML, JavaScript, CSS, and even plain text. It can work in both web and standalone environments. It has more power than JPS and is in charge of rendering dynamic content on the UI.

2. How does Thymeleaf display data?

Spring Boot Thymeleaf Display Database Record Listing

  • Configure the data source.
  • Create an Entity.
  • Create a Controller.
  • Create a view template.

3. Is Thymeleaf better than Angular?

Angular is for making things work, and Thymeleaf is for making things look good. Also, you could say that Thymeleaf combines a template with a data model and functionality to make the end result, while AngularJS gives an application real functionality.

4. Can we use Thymeleaf without Spring?

Without spring web #1640, Thymeleaf won't work.

5. Can we use Thymeleaf with REST API?

Thymeleaf is an HTML, XML, JavaScript, CSS, and text template engine written in Java. Use angular or another client-side rendering framework when working with a JSON API that requires parsing JSON. Thymeleaf is not the way to go with REST.

6. How do you compare two strings in Thymeleaf?

In thymeleaf, you can even do a comparison of String objects. Thymeleaf uses the String internally. using the compareTo() function on the Comparable interface. To rephrase, if two items are Comparable, you can make a comparison between them.

7. What do you call Ajax in Thymeleaf?

Use the url set in the form's th:action to make an ajax call. Put the form data in order. This will be sent as an object to your controller so that it can use it. Replace that part of your HTML code with the fragment that was returned.

8. Is Thymeleaf an MVC?

Thymeleaf is a template engine used by Spring MVC to generate view pages. It offers complete Spring integration and was created to replace JSP as the view page in Spring MVC. Thymeleaf is preferable to utilize when developing web applications.

9. Can we use bootstrap in Thymeleaf?

We can add a bootstrap CSS file to the Thymeleaf template in two ways: Using bootstrap CSS CDN remote links. The Bootstrap CSS file is downloaded locally, added to the project, and then a file path is added to the Thymeleaf template.

10. How do you write code in Thymeleaf?

In Thymeleaf, a link is wrapped in @, and $ is used to get to a model object. Note that the th:object attribute of this form tag points to the name of the model object that was sent by the Spring MVC controller. The name of the object's field in the model is given by the th:field attribute.

Conclusion

The Thymeleaf view has been covered in this section. Thymeleaf is an XML attributes-based engine. The engine examines attribute values to construct a DOM tree. By basing templates on characteristics, they can be treated as simple, static HTML files that can be shown in the browser without the need for a web application server. This is one reason why Thymeleaf is so amazing. 

Enroll your names on Core Java Training to know about the spring features that help to gain knowledge for your course

Job Support Program

Online Work Support for your on-job roles.

jobservice

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:

  • Pay Per Hour
  • Pay Per Week
  • Monthly
Learn MoreGet Job Support
Course Schedule
NameDates
Core Java TrainingDec 24 to Jan 08View Details
Core Java TrainingDec 28 to Jan 12View Details
Core Java TrainingDec 31 to Jan 15View Details
Core Java TrainingJan 04 to Jan 19View Details
Last updated: 16 Aug 2023
About Author

 

Madhuri is a Senior Content Creator at MindMajix. She has written about a range of different topics on various technologies, which include, Splunk, Tensorflow, Selenium, and CEH. She spends most of her time researching on technology, and startups. Connect with her via LinkedIn and Twitter .

read less
  1. Share:
Java Articles