Full Information on utilizing Thymeleaf with Spring Boot

[ad_1]

Thymeleaf is a Java-based server-side template engine. It course of HTML5, XML, and XHTML and many others. Thymeleaf can work in each internet and non-web environments. Thymeleaf may be simply built-in with Spring and Spring Boot functions. It’s primarily used for view layers in internet MVC functions.

Spring boot makes it extraordinarily straightforward to combine and use Thymeleaf in spring boot functions. On this article, we are going to find out how we are able to use Thymeleaf to construct our view layer of the spring boot software. It is going to be defined with the assistance of examples.

Learn how to combine Thymeleaf with Spring Boot?

Spring boot already comes with Thymeleaf assist. Much like different most-used dependencies, auto-configuration for this template engine can be offered in Spring boot. We simply want so as to add the starter dependency for Thymeleaf.

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

No extra configuration is required. It’s auto-managed by the starter dependency.

Nevertheless, To be able to use Thymeleaf tags in our HTML pages, we have to add assist for Thymeleaf utilizing beneath:

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
...
</html>

Learn how to entry Mannequin Attributes in Thymeleaf?

The very first thing we require in an internet MVC software is to cross some information from the controller to view. That information is then parsed to point out on the person display. Within the spring boot software, we add varied mannequin attributes which are handed to the view. We’re going to find out how these mannequin attributes are learn and parsed within the Thymeleaf template.

String Mannequin Attribute in Thymeleaf

We use th:textual content=”${attributename}” after we entry easy mannequin attributes like String. Suppose, we have now added the beneath mannequin attribute in our controller class:

mannequin.addAttribute("identify","John");

Beneath is our HTML code/Thymeleaf to show the above mannequin attribute in view:

<p th:textual content="${identify}"></p>

Integer / Boolean Mannequin Attribute in Thymeleaf

Equally, int and boolean mannequin attributes can be accessed with ${attributeName}. Here’s a small instance:

mannequin.addAttribute("id",1);
mannequin.addAttribute("lively",true);

Beneath HTML is used to print 1 and true in view:

<p th:textual content=${id}/>
<p th:textual content=${lively}/>

Mannequin Attribute Checklist in Thymeleaf

One of the crucial requested questions on Thymeleaf is how one can ship an inventory of objects into Thymeleaf and how one can iterate an inventory in Thymeleaf and print record values.

Let’s suppose, we have now an Worker object and it has states id, identify, and many others. Now, our controller is sending an inventory of staff to Thymeleaf.

public class Worker {
	personal Lengthy id;
	personal String identify;
    // Constructor, Setters, Getters ...
}

Let’s see our controller code so as to add an inventory of staff within the mannequin attribute:

Checklist<Worker> staff = new ArrayList<>();
// Right here Worker objects are getting added within the staff record
mannequin.addAttribute("staff", staff);

Lastly, we are going to take a look at how one can iterate over the record in Thymeleaf spring boot. We use th:every in Thymeleaf to iterate over the record or every other assortment. It will loop the enclosing tags for n variety of occasions, the place n is the scale of the record. It extracts and presents every object from the record in an object and we are able to merely print it. Let’s take a look at the code to grasp higher:

	<desk type="border:strong 1px black;">
		<thead>
			<tr>
				<th>ID</th>
				<th>NAME</th>
			</tr>
		</thead>
		<tbody>
			<tr th:every="worker: ${staff}">
				<td th:textual content="${worker.id}" />
				<td th:textual content="${worker.identify}" />
			</tr>
		</tbody>
	</desk>

Within the above instance, staff is the record object which we have now added in mannequin attributes. worker represents the item current within the staff record on the present place.

Mannequin Attribute Map in Thymeleaf

Equally, we are able to iterate every other assortment like Map in Thymeleaf. Iterating over Map differs from iterating over Checklist in Thymeleaf as a result of the previous have key,worth construction.

Let’s straight bounce into code to grasp how one can iterate over Map in Thymeleaf. Beneath is our controller code:

Map<Lengthy, String> employeeMap = new HashMap<>();
//staff is the record of Worker objects
for (Worker emp : staff) {
    employeeMap.put(emp.getId(), emp.getName());
}
mannequin.addAttribute("employeesMap", employeeMap);

Let’s take a look at the Thymeleaf template to iterate and print Map:

<desk type="border:strong 1px black;">
    <thead>
	    <tr>
		    <th>ID</th>
			<th>NAME</th>
		</tr>
	</thead>
	<tbody>
		<tr th:every="emp: ${employeesMap}">
			<td th:textual content="${emp.key}" />
			<td th:textual content="${emp.worth}" />
		</tr>
	</tbody>
</desk>

Now, we’re utilizing key and worth key phrases to get the important thing and worth for the map respectively.

If-Else Circumstances in Thymeleaf

We will impose if-else situations in Thymeleaf. If-else situations are carried out in Thymeleaf utilizing if and until key phrases. We use tags th:if and th:until for imposing if and else situations respectively.

Let’s introduce boolean values in our controller and cross them to our view through mannequin attribute.

mannequin.addAttribute("lively", true);

Let’s see Thymeleaf template:

<p>Consumer is 
    <span th:if="${lively}" th:textual content="Lively"></span>
    <span th:until="${lively}" th:textual content="Inactive"></span>
</p>

The end result will probably be “Consumer is Lively” if lively is true in any other case “Consumer is Inactive”.

Swap Case in Thymeleaf

We will use th:swap and th:case to implement swap circumstances in Thymeleaf. Let’s take a look at the instance. We’ve launched yet one more String variable division in our earlier Worker class.

public class Worker {
...
personal String division;

//getters and setters
...
}

We are going to modify our controller class so as to add division mannequin attribute and cross it to the view / Thymeleaf template:

Checklist<String> departments = new ArrayList<>();

departments.add("IT");
departments.add("INFRA");
departments.add("CS");
departments.add("HR");
departments.add("ADMIN");
		
for (int i = 0; i < 5; i++) {
    Worker emp = new Worker();
	emp.setId((lengthy)i+1);
	emp.setName("Emp "+emp.getId());
	emp.setDepartment(departments.get(i));	
    service.addEmployee(emp);		
}

Checklist<Worker> staff = service.getAll();
mannequin.addAttribute("staff", staff);

Let’s implement th:swap and th:case :

<desk type="border: strong 1px black;">
		<thead>
			<tr>
				<th>ID</th>
				<th>NAME</th>
				<th>DEPARTMENT</th>
			</tr>
		</thead>
		<tbody>
			<tr th:every="worker: ${staff}">
				<td th:textual content="${worker.id}" />
				<td th:textual content="${worker.identify}" />
				<td th:swap="${worker.division}">
				 <span th:case="'INFRA'" th:textual content="Infrastructure"></span>
				 <span th:case="'CS'" th:textual content="Buyer Help"></span>
				 <span th:case="'HR'" th:textual content="Human Sources"></span>
				 <span th:case="'ADMIN'" th:textual content="Administration"></span>
				 <span th:case="'IT'" th:textual content="Info Expertise"></span>
				</td>

			</tr>
		</tbody>

Fetch and Show Values from a Properties File(software.properties)

We are going to now retrieve values from the software.properties worth and show it utilizing Thymeleaf. We will use @surroundings.getProperty() straight into the Thymeleaf template to extract the values from a properties file.

// suppose, we have now a "app.identify" property in properties file
<p th:textual content="${@surroundings.getProperty('app.identify')}"/>

Varieties in Thymeleaf

We’ve completely different attributes in Thymeleaf to deal with person enter in a type. Attribute th:motion is used for offering the motion URL of the shape, th:object defines the identify of the item related to the shape, and th:subject attributes inside the shape signify the state(fields) related to the item.

Let’s perceive it with assist of an instance. Right here, we’re enhancing our current instance of Workers. As a substitute of making staff within the backend, we are going to now create the Worker utilizing Thymeleaf types:

<type motion="#" th:motion="@{/add}" th:object="${worker}"
		technique="put up">
		<desk>
			<tr>
				<td><label th:textual content="Title" /></td>
				<td><enter sort="textual content" th:subject="*{identify}" /></td>
			</tr>
			<tr>
				<td><label th:textual content="Division" /></td>
				<td><choose th:subject="*{division}">
						<possibility th:worth="'INFRA'" th:textual content="Infrastructure"></possibility>
						<possibility th:worth="'CS'" th:textual content="Customer_Support"></possibility>
						<possibility th:worth="'HR'" th:textual content="Human_Resources"></possibility>
						<possibility th:worth="'ADMIN'" th:textual content="Administration"></possibility>
						<possibility th:worth="'IT'" th:textual content="Information_Technology"></possibility>
				</choose></td>
			</tr>
			<tr>
				<td><enter sort="submit" worth="Submit" /></td>
			</tr>
		</desk>
	</type>

Let’s perceive the instance:

  • th:motion="@{/add}" make a name to the controller with /add mapping after submission of type.
  • technique="put up" ensures the decision will probably be made to PostMapping.
  • th:object="${worker}" defines that this type information represents object worker.
  • This worker object has been handed to Thymeleaf via Mannequin Attribute from the controller which redirected to this type. Like this: mannequin.addAttribute("worker", new Worker());
  • th:subject="*{identify}" binds the offered subject to the item. For instance, right here identify represents worker.identify and worth offered on this enter subject will probably be certain to worker.identify.

The above type after submission will name the beneath controller technique:

	@PostMapping("/add")
	public String addEmployee(@ModelAttribute Worker worker) {	
		service.addEmployee(worker);
		return "redirect:/staff";
	}

We’ve returned “redirect:/staff” that’ll name the controller technique with /staff mapping. On this technique, we’re retrieving the record of staff and passing it to view.

Conclusion

On this tutorial, we have now discovered Thymeleaf with examples. Beginning with the mixing of Thymeleaf in Spring Boot until utilizing it within the software of spring boot, we tried to cowl every little thing about Thymeleaf with Spring Boot.

[ad_2]

Source_link

Leave a Comment