I start by including the thymeleaf maven dependency into pom.xml
<dependency> <groupId>org.thymeleaf</groupId> <artifactId>thymeleaf-spring4</artifactId> <version>2.1.4.RELEASE</version> </dependency>
Next, we set up the Beans
@Bean @Description("Thymeleaf template resolver serving HTML 5") public ServletContextTemplateResolver templateResolver() { ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(); templateResolver.setPrefix("/WEB-INF/view/"); templateResolver.setSuffix(".html"); templateResolver.setTemplateMode("LEGACYHTML5"); templateResolver.setOrder(1); templateResolver.setCacheable(false); return templateResolver; } @Bean @Description("Thymeleaf template engine with Spring integration") public SpringTemplateEngine templateEngine() { SpringTemplateEngine templateEngine = new SpringTemplateEngine(); templateEngine.setTemplateResolver(templateResolver()); templateEngine.addDialect(new LayoutDialect()); return templateEngine; } @Bean @Description("Thymeleaf view resolver") public ThymeleafViewResolver viewResolver() { ThymeleafViewResolver viewResolver = new ThymeleafViewResolver(); viewResolver.setTemplateEngine(templateEngine()); return viewResolver; }
*** In the templateResolver bean, I've set up the folder path for the view templates as /WEB-INF/view/
Next, to check if Thymeleaf works correctly, lets's create a method in a Controller
@RequestMapping("/test") public String helloTest(Model model){ model.addAttribute("var1", "Hello World!"); model.addAttribute("varDate", Calendar.getInstance()); return "test"; }
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> This is a TEST <h3>Text</h3> <p th:text="'Hello Thymeleaf!'">Welcome to our grocery store!</p> <h3>Link</h3> <p>You may click <a href="http://www.google.com" th:href="@{http://www.quizcv.com}">here</a> </p> <h3>Variable</h3> <p th:text="${var1}">var1</p> <h3>Thymeleaf Utils</h3> <p th:text="${#calendars.format(varDate,'dd MMMM yyyy')}">Current Date</p> </body> </html>
- th:text replaces the text value
- th:href replaces the link value
- Passing a variable from the controller to the view:
- ${var1} is replaced with the variable that controller provided
- we used Thymeleaf's util's #calendars.format to format the Calendar variable (varDate) that is provided by the controller.
We see that the controller returns a string that is actually the name of a view template that Thymeleaf is processing.
Hiç yorum yok:
Yorum Gönder