Search⌘ K
AI Features

Refactor the Table Using Fragments

Explore how to refactor table structures in a Spring Boot application by creating reusable Thymeleaf fragments for table headers and data cells. Understand how to apply parameters and conditional styling to reduce code duplication and improve maintainability in your web pages.

We'll cover the following...

So far, things already look pretty good in the browser, but we still have significant duplication in the <th> and <td> tags.

Creating fragments

Let’s create a few small fragments to avoid that. This is how the <th> tag is currently used:

HTML
<tr>
<th class="px-6 py-3 border-b border-gray-200 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
Name
</th>
<th class="px-6 py-3 border-b border-gray-200 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
Gender
</th>
<th class="px-6 py-3 border-b border-gray-200 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
Birthday
</th>
<th class="px-6 py-3 border-b border-gray-200 bg-gray-50 text-left text-xs leading-4 font-medium text-gray-500 uppercase tracking-wider">
Email
</th>
<th class="px-6 py-3 border-b border-gray-200 bg-gray-50"></th>
</tr>

Let’s create a new fragment table.html to put in all the table related fragments. We’ll also add a fragment header that represents how we want to style our table headers:

 ...