Spring Boot / Thymeleaf: Fragments via Ajax

This is probably not the best approach and you guys can feel free to correct me in the comments section, but here is a simple tutorial on how I’m getting my fragments loaded via ajax.
Same as before, the full project is on my Github: https://github.com/mtrojahn/spring-thymeleaf-fragments-from-ajax
Let’s get to it:
MyController.groovy
@Controller class MyController { @GetMapping(['/', '/index.html']) def index(Model model) { 'index' } @GetMapping('/frag1') def frag1(Model model) { model.addAttribute("content", "hello") "fragments/frag1 :: content" } @GetMapping('/frag2') def frag2(Model model) { model.addAttribute("content", "world") "fragments/frag2 :: content" } }
Very simple controller. Nothing special except for the fact it’s returning Thymeleaf fragmets from /resources/templates/fragments. As you probably noticed, for the sake of this example, each fragment is recieving it’s “content” from the controller.
Here’s a fragment: frag1.html
<th:block th:fragment="content" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <div th:text="${content}"></div> </th:block>
Now the index.html
<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"/> <title>Title</title> <script src="webjars/jquery/3.1.0/jquery.js"></script> </head> <body> <button id="bt1">Load Fragment 1</button> <button id="bt2">Load Fragment 2</button> <div id="content"></div> <script> /*<![CDATA[*/ $("#bt1").on("click", function () { $("#content").load("/frag1"); }); $("#bt2").on("click", function () { $("#content").load("/frag2"); }); /*]]>*/ </script> </body> </html>
Each button has it’s event and is calling a different method on the controller. The method then returns the corresponding fragment that will be loaded on the content div.
Pretty simple, huh?