Reuse More Code With ThymeLeaf Layouts

As you saw in the last entry you can use ThymeLeaf Fragments to split out reusable parts of your html pages so that you can just drop them in where needed just like Custom Controls in XPages. Another great XPage concept was using a Custom Control to design the main layout of your page and then drop the content for the page that you are displaying in to a facet on that custom control. With an add-on to ThymeLeaf, which is automatically supplied when using ThymeLeaf with SpringBoot, this is also easily achievable.

I’ve created a new folder in my resources section called ‘layouts’ and I’ve pulled over a copy of my homepage that I will convert in to a layout.  I forst need to add the xml namespace in to the HTML tag and then I can add a div with a tag of layout:fragment to the sections that will be replaced with the content that I’m supplying.

You will also see that I’m still including some ThymeLeaf fragments as defined in the last blog entry, and I have changed how the head tag is setup by adding in a th:block ( because div is invalid in the head tag )  and for the title tag I now have a new layout:title-pattern tag that allows me to programmatically define the title using a combination of the layouts title and then contents title.

Over on my home page I can now add the same namespace and also specify which layout I will be using by adding in a layout:decorate tag.

The system will now merge the <head> elements from both the layout and the content pages  and then replace the layout fragments in the layout page with the layout fragments in the content page while ignoring anything else in the content page that is not part of the fragments.

Over on my location page you can see where I am adding a ThymeLeaf fragment in the header for the DataTables CSS and where I have specified the custom-footer fragment so that I can also add in the DataTables scripts.

As you can see a combination of ThymeLeaf Fragments and ThymeLeaf Layouts is very powerful and this is just scratching the surface of what ThymeLeaf can do.

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