투케이2K

20. (spring/스프링) [thymeleaf/타임리프] 자주 사용하는 th 기본 문법 설명 - text , if else , switch , for 본문

Spring

20. (spring/스프링) [thymeleaf/타임리프] 자주 사용하는 th 기본 문법 설명 - text , if else , switch , for

투케이2K 2021. 8. 20. 18:11
반응형

[개발 환경 설정]

개발 툴 : inteli j

개발 언어 : spring


[소스코드 : templates >> testThymeleafLang.html]

<!-- body 시작 부분 -->
<body>

<!--
[타임리프 자주 사용 문법 설명]
1. 타임리프는 th 키워드를 사용해서 문법을 사용합니다

2. th 키워드를 사용하기 위해서는 <html> 부분에 th 설정을 해줘야합니다
   - <html lang="en" xmlns:th="http://www.thymeleaf.org">

3. 주요 th 종류 설명
   - th:text - 텍스트 지정의미입니다
   - th:value - value 값 지정의미입니다 (폼 양식)
   - th:each - for 반복문 의미입니다 (값이 하나 일 경우 단순 변수 지정으로도 사용가능)
   - th:if / th:unless - if , else 구문입니다
   - th:switch / th:case - switch 분기 처리 구문입니다

4. 주요 표현식 설명
   - ${} - key 값을 지정할 때 사용하는 변수입니다

5. 주요 연산자 설명 (th:타입 = "구문내에서 연산자 사용")
   - and , or , not , 크기 비교 연산자 (< (gt) , > (lt) , >= (ge) , <= (le))
-->



<!-- [문법] th:text="${key}" : 텍스트 지정 = 특정 key 변수 호출 -->
<div style="top: 2%;">
  <!--
  [컨트롤러에서 지정한 model 모델 형식]
  model.addAttribute("name", "twok"); // [key, value]
  model.addAttribute("age", 28); // [key, value]
  model.addAttribute("sex", "M"); // [key, value]
   -->
  <p>
    <span class="title">[문법] th:text="${key}" : 텍스트 지정 = 특정 key 변수 호출</span><br>
    이름 : <span th:text="${name}"></span><br>
    나이 : <span th:text="${age}"></span><br>
    성별 : <span th:text="${sex}"></span><br>
  </p>
</div>



<!-- [문법] th:each="n_data : ${name}" th:text="${n_data}" : 단순 변수 지정 및 데이터 결합 -->
<div style="top: 4%;">
  <!--
  [컨트롤러에서 지정한 model 모델 형식]
  model.addAttribute("name", "twok"); // [key, value]
  model.addAttribute("age", 28); // [key, value]
  model.addAttribute("sex", "M"); // [key, value]
   -->
  <p>
    <span class="title">[문법] th:each="n_data : ${name}" th:text="${n_data}" : 단순 변수 지정 및 데이터 결합</span><br>
    이름 : <span th:each="n_data : ${name}" th:text="${n_data} + ' 입니다'"></span><br>
    나이 : <span th:each="a_data : ${age}" th:text="${a_data} + ' 입니다'"></span><br>
    성별 : <span th:each="s_data : ${sex}" th:text="${s_data} + ' 입니다'"></span><br>
  </p>
</div>



<!-- [문법] th:if / th:unless : if else 조건문 처리 -->
<div style="top: 6%;">
  <!--
  [컨트롤러에서 지정한 model 모델 형식]
  model.addAttribute("name", "twok"); // [key, value]
  model.addAttribute("age", 28); // [key, value]
  model.addAttribute("sex", "M"); // [key, value]
   -->
  <p>
    <span class="title">[문법] th:if / th:unless : if else 조건문 처리</span><br>
    이름 : <span th:if="${name}=='twok'" th:text="'IF twok'"></span><span th:unless="${name}=='twok'" th:text="'ELSE twok'"></span><br>
    이름 : <span th:if="${name}=='투케이'" th:text="'IF 투케이'"></span><span th:unless="${name}=='투케이'" th:text="'ELSE 투케이'"></span><br>
  </p>
</div>



<!-- [문법] th:switch / th:case : switch 문 분기 처리 실시 -->
<div style="top: 8%;">
  <!--
  [컨트롤러에서 지정한 model 모델 형식]
  model.addAttribute("name", "twok"); // [key, value]
  model.addAttribute("age", 28); // [key, value]
  model.addAttribute("sex", "M"); // [key, value]
   -->
  <p>
    <span class="title">[문법] th:switch / th:case : switch 문 분기 처리 실시</span><br>

    이름 :
    <span th:switch="${name}">
      <span th:case="'투케이1'">1번 투케이</span>
      <span th:case="'투케이2'">2번 투케이</span>
    </span>
    <span th:unless="${name} == '투케이1' or ${name} == '투케이2'">ELSE 투케이</span>
    <br>

  </p>
</div>



<!-- [문법] th:each : List 객체 데이터 for 반복 출력 실시 -->
<div style="top: 10%;">
  <!--
  [컨트롤러에서 지정한 model 모델 형식]
  List<Insert_Each_List_Model> tables = new ArrayList<>();
  for (int i=1; i<=5; i++){
    // 이름 / 나이 / 성별 데이터 삽입
    tables.add(new Insert_Each_List_Model(name+String.valueOf(i), String.valueOf(i), "M"));
  }
  model.addAttribute("tableList", tables); //value 값에 객체 지정 실시
   -->
  <p>
    <span class="title">[문법] th:each : List 객체 데이터 for 반복 출력 실시</span><br>

    <span th:each="list : ${tableList}">
      <span th:text="' 이름 : ' + ${list.name}"></span>
      <span th:text="' 나이 : ' + ${list.age}"></span>
      <span th:text="' 성별 : ' + ${list.sex}"></span>
      <br>
    </span>

  </p>
</div>



</body>

[소스코드 : controller >> ThymeLeafController]

    // [get : map 방식]
    // [경로 지정 : http://localhost:7000/testThymeleafLang]
    // [api 로직 : 사용자가 url 접속 시 >> 로직 처리 후 >> testThymeleafLang.html로 리턴(뷰 이동)합니다]
    // [html 로직 : testThymeleafLang.html은 api에서 리턴 받은 데이터를 표시해줍니다]

    @GetMapping("/testThymeleafLang")
    public String testThymeleafLang(@RequestParam Map<String, String> param, Model model){
        System.out.println("\n");
        System.out.println("=======================================");
        System.out.println("[ThymeLeafController] : [testThymeleafLang] : [start]");
        System.out.println("=======================================");
        System.out.println("\n");

        // [Model (모델) 에 일반 key , value 지정 실시]
        model.addAttribute("name", "twok"); // [key, value]
        model.addAttribute("age", 28); // [key, value]
        model.addAttribute("sex", "M"); // [key, value]

        // [Model (모델) 에 리스트 객체 데이터 삽입 실시]
        String name = "twok";
        List<Insert_Each_List_Model> tables = new ArrayList<>();
        for (int i=1; i<=5; i++){
            // 이름 / 나이 / 성별 데이터 삽입
            tables.add(new Insert_Each_List_Model(name+String.valueOf(i), String.valueOf(i), "M"));
        }
        model.addAttribute("tableList", tables); //value 값에 객체 지정 실시

        // [testThymeleafLang.html 호출]
        return "testThymeleafLang";
    }
​

[소스코드 : model >> Insert_Each_List_Model]

package com.project.solutionpackage.model;

import lombok.Data;

@Data
public class Insert_Each_List_Model {

    /**
     * [클래스 설명]
     * 1. insert 포맷 형태 정의 클래스
     * 2. controller 에서 사용한다
     * */

    private String name;
    private String age;
    private String sex;

    public Insert_Each_List_Model(String name, String age, String sex) {
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

}

[결과 출력]


[요약 설명]

<!--

[타임리프 자주 사용 문법 설명]

1. 타임리프는 th 키워드를 사용해서 문법을 사용합니다

2. th 키워드를 사용하기 위해서는 <html> 부분에 th 설정을 해줘야합니다

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

3. 주요 th 종류 설명

- th:text - 텍스트 지정의미입니다

- th:value - value 값 지정의미입니다 (폼 양식)

- th:each - for 반복문 의미입니다 (값이 하나 일 경우 단순 변수 지정으로도 사용가능)

- th:if / th:unless - if , else 구문입니다

- th:switch / th:case - switch 분기 처리 구문입니다

4. 주요 표현식 설명

- ${} - key 값을 지정할 때 사용하는 변수입니다

5. 주요 연산자 설명 (th:타입 = "구문내에서 연산자 사용")

- and , or , not , 크기 비교 연산자 (< (gt) , > (lt) , >= (ge) , <= (le))

-->


​[파일 첨부]

소스코드.txt
0.01MB


 

반응형
Comments