Separated layout from content with Thymeleaf
authorKai Moritz <kai@juplo.de>
Thu, 16 Jan 2020 09:16:23 +0000 (10:16 +0100)
committerKai Moritz <kai@juplo.de>
Thu, 16 Jan 2020 10:01:24 +0000 (11:01 +0100)
src/main/java/de/juplo/demo/HtmlController.java
src/main/resources/templates/home.html [new file with mode: 0644]
src/main/resources/templates/layout.html
src/test/java/de/juplo/demo/HtmlControllerTest.java

index eaa2fcc..5696718 100644 (file)
@@ -27,6 +27,6 @@ public class HtmlController
   public String fetch(Model model, @RequestParam String path)
   {
     model.addAttribute("text", service.getRemoteText(path));
-    return "layout";
+    return "home";
   }
 }
diff --git a/src/main/resources/templates/home.html b/src/main/resources/templates/home.html
new file mode 100644 (file)
index 0000000..6076f98
--- /dev/null
@@ -0,0 +1,13 @@
+<!doctype html>
+<html lang="en" xmlns:th="http://www.thymeleaf.org"  th:replace="~{layout :: pagelayout(~{:: title}, ~{:: h1}, ~{:: div.card-text})}">
+  <head>
+    <meta charset="utf-8">
+    <title>Shows Remote-Content</title>
+  </head>
+  <body>
+    <h1>Fetched Data</h1></div>
+    <div class="card-text">
+      <pre th:text="${text}">TEXT</pre>
+    </div>
+  </body>
+</html>
index bc5799a..233b937 100644 (file)
@@ -1,9 +1,9 @@
 <!doctype html>
-<html xmlns:th="http://www.thymeleaf.org" lang="en">
+<html lang="en" xmlns:th="http://www.thymeleaf.org" th:fragment="pagelayout(title,header,body)">
   <head>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
-    <title>Shows Remote-Content</title>
+    <title th:replace="${title}">TITLE</title>
     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
   </head>
   <body>
       <h2 class="navbar-brand">Demo: Unit-Test or Integration-Test &mdash; A Practical Guide</h2>
     </nav>
     <main class="container mt-5">
-      <div class="card">
-        <div class="card-header" id="content"><h1>Information About Fetched Data</h1></div>
-        <div class="card-body">
-          <p class="card-text"><pre th:text="${text}">TEXT</pre></p>
-        </div>
+      <div id="content" class="card">
+        <div class="card-header"><h1 th:replace="${header}">HEADER</h1></div>
+        <div class="card-body"><div th:replace="${body}">BODY</div></div>
       </div>
     </main>
   </body>
index ceb14e4..1cf7274 100644 (file)
@@ -47,7 +47,7 @@ public class HtmlControllerTest
 
     String result = controller.fetch(model, "foo");
 
-    assertThat(result).isEqualTo("layout");
+    assertThat(result).isEqualTo("home");
     ArgumentCaptor<Mono<String>> captor = ArgumentCaptor.forClass(Mono.class);
     verify(model).addAttribute(eq("text"), captor.capture());
     StepVerifier