상세 컨텐츠

본문 제목

Thymeleaf(타임리프) 기본문법

프레임워크/Thymeleaf

by 최승호 2022. 5. 18. 12:00

본문

타임리프란?

https://www.thymeleaf.org/

 

Thymeleaf

Integrations galore Eclipse, IntelliJ IDEA, Spring, Play, even the up-and-coming Model-View-Controller API for Java EE 8. Write Thymeleaf in your favourite tools, using your favourite web-development framework. Check out our Ecosystem to see more integrati

www.thymeleaf.org

타임리프는 HTML, XML, JavaScript, CSS 및 일반 텍스트를 처리할 수 있는 서버 사이트 Java 템플릿 엔진이다.

Spring Boot는 템플릿 엔진으로 FreeMaker, Thymeleaf, Mustache 등을 지원하며 src/main/resources/templates 경로에서 자동으로 인식된다. 기존 JSP가 로직이 직접적으로 템플릿에 사용되었던것에 비해 타임리프는 기존 템플릿에 영향을 미치지 않으면서 논리적인 로직을 삽입할 수 있다는 장점이 있다.

타임리프 문서 정의

<html xmlns:th="http://www.thymeleaf.org">

 

타임리프에서 제공하는 기능을 사용하기 위해 html 문서 정의 부분에 위 속성을 추가한다.

컨트롤러를 통해 html 페이지 호출

HomeController.java

@Controller
public class HelloController {
    
    @RequestMapping("/")
    public String home(Model model) {
        model.addAttribute("data", "hello 안녕하세요");
        return "home";
    }
}

 

home.html

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Hello</title>
</head>
<body>
    <p th:text="${data}">Hello!!</p>
</body>
</html>

th:text

일반 텍스트를 표기할 수 있다.

Expression

${x} : context 혹은 rqeust attribute 저장된 변수 x를 호출

${param.x} : request parameter 에서 x를 호출

${session.x} : session attribute 에서 x를 호출

${application.x} : servlet contex attribute 에서 x를 호출

 

실행결과

 

'프레임워크 > Thymeleaf' 카테고리의 다른 글

Thymeleaf(타임리프) 기본문법 - 표현식  (0) 2022.05.20

관련글 더보기

댓글 영역