Introducing ThymeLeaf Fragments

When I created my people by location page I just copied the entire home page of the application. I now want to make a few changes to the side navigator but if I leave things as they are now I would have to make those changes in all pages that share the side navigator. In the XPages world we had custom controls which could be used to break your page in to separate components and ThymeLeaf has a similar concept called Fragments.

Under my templates folder I’m going to create a new folder called fragments and in there I’m going to add a new html page called layout.html. I’m then going to move the html that makes up the side navigator to this html file and add in an extra ThymeLeaf tag.

This tag identifies the div and everything between it and the closing div as the fragment called ‘sidenav’.

Now back on both the home and location pages I can replace that entire block of code with one simple line.

This tag tells the ThymeLeaf processor to replace this entire div ( and anything in the div ) with the fragment called ‘sidenav’ from the file called layout in the fragments folder.

If you restart the application now you won’t see any changes on the page but the side navigation bar is no longer duplicated across multiple pages so if you need to change it then you just have to update one file.

You can add as many fragments as you want to a single fragment file or you could split them up in to different files. You could even use fragments to set all your head tags or load your scripts. I’ve setup a fragment for my global scripts and I have added an additional ThymeLeaf tag of th:remove=”tag”.

What this does is it will remove the

tags and only render the contents which, in this case, are the two script tags.

If you are using a fragment to setup all your css then you may run in to the issue of how to set a page title. To do this you can add parameters to a fragment. Here I’ve added a pageTitle parameter and I’m using it in the title tag.

When I call this fragment I can then pass in a value to the parameter.

or you could even calculate a title using a ThymeLeaf Expression

So now you can break your application up in to smaller chunks and make reusable code sections for the frontend.

Advertisements
Tagged with:
Posted in Domino To Spring
Archives
%d bloggers like this: