Menu Item Components

Learn to refactor the code of menu items by eliminating duplication in fragments.

Our index.html is already looking a lot better, but we still have a lot of duplication in our fragments themselves.

In the menu on the left side, each menu item looks similar to this:

Press + to interact
<a href="#"
class="mt-1 group flex items-center px-2 py-2 text-sm leading-5 font-medium textgray-
900 rounded-md bg-gray-100 hover:text-gray-900 hover:bg-gray-100 focus:outlinenone
focus:bg-gray-200 transition ease-in-out duration-150">
<svg class="mr-3 h-6 w-6 text-gray-500 group-hover:text-gray-500 group-focus:textgray-
600 transition ease-in-out duration-150"
fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0
01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"/>
</svg>
Dashboard
</a>

The structure of menu items

We can identify the following structure:

  • The <a> HTML tag identifies the item as a link that can be clicked to navigate to that part of the application.
  • The href attribute indicates where to link to.
  • The <svg> child element contains the relevant icon for the menu item.
  • The “dashboard” text is shown to the user for the link.
  • The class attribute styles the menu item

Note: There is a slight difference in the class list as the Dashboard item is styled to look selected, while the others are not.

Creating a fragment

Let’s create a fragment. Start with a file sidebar-buttons.html to put our fragment in:

Press + to interact
<html xmlns:th="http://www.thymeleaf.org">
<!--/*@thymesVar id="link" type="java.lang.String"*/-->
<!--/*@thymesVar id="title" type="java.lang.String"*/-->
<a th:fragment="desktop-button(link, title)"
th:href="${link}">
[[${title}]]
</a>
</html>

This gives us the basic structure to work with. We then declare the following two parameters to our fragment:

  • link
  • title
...