Spring Thymeleaf Tips | Part 3


Thymeleaf Fragments, Projection and Selection

I’m back again with the third (and final) installment of our exploration of some of the finer points of Spring’s Thymleaf templating system. Today we’re going to go over a couple of complex topics in more detail. Fragments give you the option to reuse a template with a th:replace tag, selection lets you filter a collection on a set of conditions and projection fattens out a collection of objects into a consumable string result.

Fragments are Your Friend

Fragments grant you a ton of power and help you create modularized components that can be reused all over your web app. The basic idea here is that you define a fragment and then you can reference that template using a th:replace anywhere in your application. Let’s take the table from Parts 1 & 2 and turn it into a fragment.

When we last left it, the body of our index.html looked like this:

To make a fragment, we create a new file (ours will be in a fragments folder, but that’s not necessary). We’re calling this file common_fragments.html.

We then use the th:fragment notation to name our table fragment.

The argument specifies the name of the object we are passing to the fragment. In this case, we’ve named it the same as in our core model – people. Next we add the table code.

And finally, we reference the fragment in our index.html using th:replace and passing in our model object:

And just like that, we’ve got a reusable piece of template that we can throw in with a single line whenever we need it.

Use Projection with Th:each to Flatten a Collection

Suppose we wanted to simplify our list down to only name and row count. We could use the projection notation to simplify this collection as follows:

It’s important to note that you can’t access other properties you didn’t reference up top after you run through projection. The object is flattened out into a simple string in the example above.

For the remaining examples, I’ve added the addresses back in so we have more data to work with.

Use the Selection with Th:each to Filter a Collection

Selection operations allow us to filter a collection on a given predicate specified in the th:each declaration. The notation looks like this:

The resulting table has the non-matching entry filtered out:

So let’s say we wanted to break this data into tables by state. We could use a combination of the concepts in this series to do it with minimal code.

First, I modify the people table fragment to take a state code:

Next, we will add a list of state codes into my model on the controller

Finally, we wrap the fragment call in index in a th:each for each code we provided in the service:

When we load the page we see:


That’s it for our series on Thymeleaf. Hopefully, you learned something new through our sampling of Thymeleaf’s feature set.  Thanks for reading!

About The Author

Andrew Ross is a Lead Consultant on the Software team.