Thymeleaf 엔진 사용해보기

Springboot는 자동화 구성 모듈을 제공하는 템플릿 엔진이 있다.

  • Thymeleaf

  • FreeMarker

  • Groovy

기본 경로는 src/main/resources/templates 이다.

JSP 는 이모 오래전 부터 springboot 권장하는 template 엔진리스트에 배제 되었다.

Thymeleaf 엔진이란?

Thymeleaf는 XML/XHTML/HTML5 템플릿 엔진으로 웹 및 비웹 환경에서 응용 및 개발에 사용할 수 있다. Apache License 2.0 라이선스를 기반으로 Daniel Fernández가 만든 오픈 소스 자바 라이브러리이며 자바 암호화 라이브러리 Jasypt의 저자이기도 함. 암호화 라이브러리 Jasypt 사용방법은 민감한 정보에 대한 암호화 에 이미 정리한적 있다.

아래 코드를 간단하게 보여주겠다.

<table>
  <thead>
    <tr>
      <th th:text="#{msgs.headers.name}">Name</td>
      <th th:text="#{msgs.headers.price}">Price</td>
    </tr>
  </thead>
  <tbody>
    <tr th:each="prod : ${allProducts}">
      <td th:text="${prod.name}">Oranges</td>
      <td th:text="${#numbers.formatDecimal(prod.price,1,2)}">0.99</td>
    </tr>
  </tbody>
</table>

사용법의 예전의 JSP와 유사하다. 그럼 한번 실제로 구성해보자

pom.xml 작성

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Controller 작성

@Controller
public class HelloController {

    @GetMapping("/")
    public String index(ModelMap map) {
        map.addAttribute("host", "http://blog.blake.com");
        return "index";
    }

}

요약

  • index 페일지를 랜더링 할때 ModleMap 을 통해서 web 페이지에 host 파라미터를 전송한다. 즉 "http://blog.blake.com" 가 바로 파라미터 이다.

  • 기본 경로 src/main/resources/templates/ 에 return 해준다.그러면 intedx.html 파일을 찾아간다.

src/main/resources/templates/ 폴더에 index.hml 파일을 만든다.

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
<h1 th:text="${host}">Hello World</h1>
</body>
</html>

Thymeleaf 의 기타 파라미터 값들 목록

# Enable template caching.
spring.thymeleaf.cache=true 
# Check that the templates location exists.
spring.thymeleaf.check-template-location=true 
# Content-Type value.
spring.thymeleaf.content-type=text/html 
# Enable MVC Thymeleaf view resolution.
spring.thymeleaf.enabled=true 
# Template encoding.
spring.thymeleaf.encoding=UTF-8 
# Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.excluded-view-names= 
# Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.mode=HTML5 
# Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.prefix=classpath:/templates/ 
# Suffix that gets appended to view names when building a URL.
spring.thymeleaf.suffix=.html  spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.

TIP! 위 설정은 아래와 같은 경우 사용하도록

  • 페이지 수정후 매번 restart 하기 귀찮다? spring.thymeleaf.cache = false

  • template 폴더의 template 를 사용하지 않겠다? spring.thymeleaf.prefix = / 새로운 폴더경로

  • index 의 확장자를 사용하지 않고 다른걸 사용하고 싶다? spring.thymeleaf.suffix=.html

  • H5 의 엄격모드를 피하고 싶다? spring.thymeleaf.mode = LEGACYHTML5 혹시 설정 예러 날 경우 아래와 같이 dependency 함께 추가해 보라

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
             <groupId>net.sourceforge.nekohtml</groupId>
             <artifactId>nekohtml</artifactId>
         </dependency>
Colored by Color Scripter

Last updated