[Thymeleaf]타임리프 시작하기

패키지 추가하기

먼저 타임리프를 사용하기 위해선 당연히 타임리프 패키지가 필요하다.
프로젝트에서 사용하는 것에 맞게 gradle 이나 maven에 추가해준다.

// gradle
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
// maven
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

기본 구성

이후 application.yml 에 가서 thymeleaf 단어를 살짝 쳐보면 인텔리제이의 경우
prefix가 나오는데 classpath:/templates/ 가 기본 경로라는 것을 알수가 있다.
여기서 경로를 바꾸고 싶다면 변경을 해준다.

보통은 templates 그대로 사용하기때문에 나도 templates 폴더를 만들고
하위에 index.html 을 만들어주었다.

// index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    Hello World!!!
</body>
</html>

이후 index 파일의 컨트롤러를 만들었습니다.

@Controller
public class MainController {

    @GetMapping("/")
    public String index(){
        return "index";
    }
}

개발의 시작인 hello world 를 작성하고 일반적인 html 파일을 띄어보았습니다.

타임리프 사용하기

이제 이 html에 타임리프를 사용하려면 html 태그에 attribute를 추가해주어야한다.

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

추가가 완료되면 타임리프 문법들을 사용할 수 있다.
th:text 는 해당 태그에 text 값을 넣어주는 기능을 한다.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" >
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <span th:text="Thymeleaf+' '+Text">Hello World!!!</span>
</body>
</html>

결과

span 태그 안에는 hello world가 있었지만 th:text 의 텍스트가 들어갑니다.
그리고 중요한점은 ‘Thymeleaf Text’로 안쓰고 +’ ‘+ 한 이유는
띄어쓰기가 안되기 때문에 주의하셔야합니다.

그리고 변수값을 사용할때는 기본적으로 ${변수}를 사용합니다.

@Controller
public class MainController {

    @GetMapping("/")
    public String index(Model model){
        model.addAttribute("indexValue","Hello Word!");
        return "index";
    }
}

indexValue 라는 값을 전달하고

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" >
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <span th:text="Thymeleaf+' '+Text">Hello World!!!</span>
    <span th:text="${indexValue}"></span>
</body>
</html>

th:text에 ${indexValue} 값이 들어가도록 했습니다.

결과

아무것도 없던 span 에 indevValue로 전달했던 hello world 가 추가된걸 볼 수 있습니다.

Leave a Comment