티스토리 뷰

Thymeleaf

[Thymeleaf] - Thymeleaf 기본문법

김종현 2020. 12. 15. 01:08

저번글에는 Thymeleaf 세팅법에 대해 알아보았는데 이번엔 기본문법을 알아보자

HTML

text 출력

<div th:text="${text}"></div> 

Thymeleaf의 표현식은 
<div>[[${text}]]</div> 
이렇게 태그 바깥에서 대괄호를 2겹으로 감싸서도 표현이 가능하다.

 

if / else

<div th:if="${data != null and data != ''}" th:text="${data}"></div>
<div th:unless="${data != null and data != ''}" th:text="비어있음"></div>
th:if는 if조건에 해당되었을때 출력이 되고 th:unless은 else에 해당되었을때 출력된다**  

여기서 한가지 이상한점이 들 것이다. 보통 조건문을 작성시 else if가 아닌 else를 쓸땐 조건식을  
명시하지 않는데 Thymeleaf의 조건식은 else문을 작성해줄때 동일한 if조건식을 명시해줘야 그 if조건에  
충족하지 않은 결과(else)가 나오게 된다.

 

html tag

<div th:utext="${tag}"></div>
서버에서 tag라는 변수에 저장된 값에 HTML 태그가 있다면 그 태그가 문자열이 아닌 HTML 태그로 변환되어진다.

 

assignment

<div th:with="name = ${data}" th:text="${name}"></div>
해당변수에 값을 할당한다. 위 if / else 에서 사용되었던 ${data}값을 name 이라는 변수에 저장후 출력한다.

 

switch, case

<div th:switch="${switch}">
    <div th:case="${case1}" th:text="'1과 같은값'"></div>
    <div th:case="${case2}" th:text="'1보다 큰 값'"></div>
    <div th:case="${case3}" th:text="'1보다 작은 값'"></div>
    <div th:case="*" th:text="'1보다 작은 음수 값'"></div>
</div>

한가지 다른점이 있다면 기존에 switch문은 해당 case에 모두 충족하지 않으면 default이지만
Thymeleaf에선 case="*"이 default에 해당한다.

 

board list

<table>
    <tbody>
        <tr th:each="board : ${boardList}">
            <td th:text="${board.idx}"></td>
            <td th:text="${board.title}"></td>
            <td th:text="${board.writer}"></td>
            <td th:text="${#dates.format(board.regDate,'yyyy-MM-dd HH:mm:ss')}"></td>
        </tr>
    </tbody>
</table>

 

select box

<select>
      <option th:each="board : ${selectBox}" th:value="${board.idx}" th:text="${board.title}">
      </option>
</select>

JAVA

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.kjh.study.model.Board;
import com.kjh.study.service.StudyService;

import lombok.RequiredArgsConstructor;

@Controller
@RequestMapping("/study")
@RequiredArgsConstructor
public class StudyController {

    private final StudyService studyService;

    @GetMapping("/list")
    public String study(Model model) {

        // text 
        model.addAttribute("text", "Hello, Thymeleaf");

        // if / else
        model.addAttribute("data", "data");

        // html tag
        model.addAttribute("tag", "<strong>hello</strong>");

        // assignment
        model.addAttribute("name", "kimjonghyun");

        // switch, case
        model.addAttribute("switch", 1);
        model.addAttribute("case1", 1);
        model.addAttribute("case2", 2);
        model.addAttribute("case3", 0);

        // board list
        model.addAttribute("boardList", studyService.selectBoardList());

        // select box
        List<Board> selectBox = new ArrayList<>();

        for (int i=0; i<5; i++) {
            Board board = new Board();
            board.setIdx(i);
            board.setTitle("제목"+i);

            selectBox.add(board);
        }

        model.addAttribute("selectBox", selectBox);

        return "study";
    }
}

결과

한가지 궁금한건 if / else 예제와 switch, case 예제를 보면 

if / else 에는 th:text값에 더블쿼트안에 싱글쿼트가 없어도 정상적으로 값이 출력되는데

switch, case에 th:text값에 더블쿼트안에 싱글쿼트가 없으면 템플릿문법예외가 발생되는데

이건 찾아봐야 할듯 싶다.

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함