JavaScript Consolidation with Thymeleaf and Spring MVC

We just added “Your Liked Posts” to NixMash Spring where a user’s liked posts are displayed in the Post Stream. (You need to be logged-in and like a few posts first…whether you like them or not. lol!)

This User Liked Posts stream brings the number of Post Stream types to five.

  1. Default Posts Stream with full post content
  2. Posts by Tag — full content
  3. Post Titles
  4. Post Titles by Tag — when tags clicked in Post Title Stream
  5. User Liked Posts — liked posts only, full content

Each display type requires its own Thymeleaf template and supporting JavaScript. With five separate pages it was time to refactor the JavaScript for re-use. The two main JavaScript functions we’re consolidating are shown in the shared Thymeleaf fragment below. (1) Populates the stream on page load from the appropriate Spring RestController endpoint and sets the stage, and (2) loads successive pages when the “More Posts” button is clicked.

Now onto Thymeleaf and how it makes it easy for us to re-use the JavaScript. More specifically, we’ll see how we pass multiple parameters to a JavaScript function with Thymeleaf.

Below is the new User Likes page with the consolidated JavaScript functions. Notice how we create a JavaScript block which the shared functions will use. That’s the key. We’re not using a Thymeleaf th:with or passing parameters to our Thymeleaf stream fragment. Just JavaScript VARS and Thymeleaf inline assignments, with a little help from Spring MVC.

Gimme some Java, Man!

It’ll be a cold day in Vermont before we write a post and not include some Java code in it, so let’s look at the PostRestController MVC tests where we confirm that all of the JavaScript var paths we’re using in the shared JavaScript functions return error-free content. The tests also confirm we’re using uniform JSON path structures across the display types.

Source Code Notes for this Post

All source code discussed in this post can be found in my NixMash Spring GitHub repo and viewed online here.