What are Fragments?
Fragments are reusable pieces of HTML that you can include in multiple pages. Think of them as templates within templates. They're perfect for headers, footers, navigation menus, and other repeated content.
The th:fragment attribute defines a fragment that can be reused elsewhere.
Fragment Parameters
Fragments can accept parameters, just like functions. This makes them flexible and dynamic.
Hello, Guest!
When you include this fragment, you can pass different names to customize the output.
Default Parameter Values
You can provide default values for fragment parameters. This makes fragments even more flexible.
Alert message
Details
If you don't pass the details parameter, it uses the default value.
Using th:replace
The th:replace attribute replaces the host tag with the fragment. This is the most common way to include fragments.
The ~{} syntax tells Thymeleaf to look for the fragment in the specified file.
Using th:insert
th:insert inserts the fragment as the body of the host tag. The host tag remains in the output.
With th:insert, the fragment becomes a child of the host element.
Using th:include
th:include includes the content of the fragment but not the fragment tag itself.
This is useful when you want just the inner content without any wrapping tags.
Try it Yourself →Fragment with Multiple Parameters
You can define fragments with multiple parameters for complex reuse scenarios.
User Name
user@example.com
Role
Now you can create different user cards by passing different parameters.