5.제어속성

리얼브로·2023년 2월 24일
0

thymeleaf

목록 보기
5/10

HTML 요소의 표시를 제어해야 하는 경우가 있는데 타임리프에서는 이런 기능을 th 속성으로 제공된다.

5-1. th:if

  • 속성 값이 참인 경우에만 대상이 되는 HTML 요소를 표시한다.

    [참과 거짓 판단 기준]

    • null 인 경우는 거짓
    • 숫자 타입에서 0이 아닌 값이면 참, 그렇지 않은 경우는 거짓
    • 문자열 타입에서 false, off, no 이면 거짓 그렇지 않은 경우는 참
    • boolean 타입, 숫자 타입, 문자열 타입 이외의 경우에는 참

    5-1-1.자바빈즈 프로퍼티 값이 null 인지 체크한다.

    • [요청] http://localhost:8080/ch0805/home0101

    • [컨트롤러 메서드]

      @GetMapping("ch0805/home0101")
      public String home0101(Model model) {
        Member member = new Member();
      
        model.addAttribute(member);
      
        return "ch0805/home0101";
      }
    • [뷰 파일]

      <html xmlns:th="http://www.thymeleaf.org">
      
      <head>
      	<title>Home</title>
      	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      </head>
      <body>
      	<th:block th:if="${member.hobbyArray == null}">
        		<p>member.hobbyArray == null</p>
      	</th:block>	
      	
      	<th:block th:if="${member.hobbyArray eq null}">
        		<p>member.hobbyArray eq null</p>
      	</th:block>	
      </body>
      </html>
    • [응답 화면]

    5-1-2.자바빈즈 프로퍼티 값이 참 인지 체크한다.

    • [요청] http://localhost:8080/ch0805/home0102

    • [컨트롤러 메서드]

      @GetMapping("ch0805/home0102")
      public String home0102(Model model) {
        Member member = new Member();
        member.setForeigner(true);
      
        model.addAttribute(member);
      
        return "ch0805/home0102";
      }
    • [뷰 파일]

      <html xmlns:th="http://www.thymeleaf.org">
      
      <head>
      	<title>Home</title>
      	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      </head>
      <body>
      	<th:block th:if="${member.foreigner}">
        		<p>member.foreigner == true</p>
      	</th:block>
      </body>
      </html>
    • [응답 화면]

    5-1-3. javascript 에서 사용

    • [뷰 파일]

      //if문
      [# th:if="${users.executivelist.size > 1}" ]
       .addSelect('empNo', '사용자', 'i18n', 100, false, {
           values: [],
           labels: [],
           editOptions: {
               listItems: executiveList
           },
           align: 'center',
           editable: true
       })         	
       [/]
      //else문
      [# th:unless="${users.executivelist.size > 1}" ]
         .add('empNo','사용자ID','i18n', 100,   false, {editable: true, visible: false})  
      [/]  
      
      또는 아래처럼 /**/ 붙여서 사용 
       
      /*[# th:if="${custInfo != null && custInfo != ''}"]*/
          var custId = $('#joinForm input[name=custId]').val();
      /*[/]*/

5-2.th:unless

  • 속성 값이 거짓인 경우에만 대상이 되는 HTML 요소를 표시한다.

    5-2-1. 자바빈즈 프로퍼티 값이 거짓인지 체크한다.

    • [요청] http://localhost:8080/ch0805/home0103

    • [컨트롤러 메서드]

      @GetMapping("ch0805/home0103")
      public String home0103(Model model) {
        Member member = new Member();
        member.setForeigner(false);
      
        model.addAttribute(member);
      
        return "ch0805/home0103";
      }
    • [뷰 파일]

      <html xmlns:th="http://www.thymeleaf.org">
      
      <head>
      	<title>Home</title>
      	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      </head>
      <body>
      	<th:block th:unless="${member.foreigner}">
        		<p>member.foreigner == false</p>
      	</th:block>
      </body>
      </html>
      
    • [응답 화면]

5-3. th:switch - th:case

  • th:switch 속성: 자식 요소에 기술된 th:case 속성의 값과 비교 평가를 하기 위한 값을 설정한다.

  • th:case 속성: 부모 요소의 th:switch 속성 값의 경우에만 대상이 되는 HTML 요소를 표시한다.

    5-3-1. th:switch 1

    • th:switch 속성 값을 비교하여 일치하는 값이 없으면 th:case="*"의 HTML 요소를 표시한다.

    • [요청] http://localhost:8080/ch0805/home0201

    • [컨트롤러 메서드]

      @GetMapping("ch0805/home0201")
      public String home0201(Model model) {
        Member member = new Member();
      
        model.addAttribute(member);
      
        return "ch0805/home0201";
      }
    • [뷰 파일]

      <html xmlns:th="http://www.thymeleaf.org">
      
      <head>
      	<title>Home</title>
      	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      </head>
      <body>
      	<div th:switch="${member.gender}">
      		<p th:case="M">male</p>
      		<p th:case="F">female</p>
      		<p th:case="*">others</p>
      	</div>
      </body>
      </html>
    • [응답 화면]

    5-3-2. th:switch 2

    th:switch 속성 값을 비교하여 일치하는 값을 가진 th:case의 HTML 요소를 표시한다.

    • [요청] http://localhost:8080/ch0805/home0202

    • [컨트롤러 메서드]

      @GetMapping("ch0805/home0202")
      public String home0202(Model model) {
        Member member = new Member();
        member.setGender("F");
      
        model.addAttribute(member);
      
        return "ch0805/home0201";
      }
    • [뷰 파일]

      <html xmlns:th="http://www.thymeleaf.org">
      
      <head>
      	<title>Home</title>
      	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      </head>
      <body>
      	<th:block th:switch="${member.gender}">
      		<p th:case="M">male</p>
      		<p th:case="F">female</p>
      		<p th:case="*">others</p>
      	</th:block>
      </body>
      </html>
      
    • [응답 화면]

5-4. th:each

  • 반복되는 HTML 요소를 표시한다.

    5-4-1.배열 타입의 자바빈즈 프로퍼티 값을 반복하여 표시한다.

    • [요청] http://localhost:8080/ch0805/home0301

    • [컨트롤러 메서드]

      @GetMapping("ch0805/home0301")
      public String home0301(Model model) {
        Member member = new Member();
      
        String[] hobbyArray = {"Music", "Movie"};
      
        member.setHobbyArray(hobbyArray);
      
        model.addAttribute(member);
      
        return "ch0805/home0301";
      }
    • [뷰 파일]

      <html xmlns:th="http://www.thymeleaf.org">
      
      <head>
      	<title>Home</title>
      	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      </head>
      <body>
      	<th:block th:each="hobby : ${member.hobbyArray}">
      		<p th:text="${hobby}">hobby</p>
      	</th:block>
      </body>
      </html>
    • [응답 화면]

    • 5-4-1-1. 반복 상태 변수 "Stat"
      • Thymeleaf에서 th:each 사용하면 반복 상태를 추적할 수 있는 status 변수를 제공해 주는데

        이를 이용하여 index, count 등의 값을 쉽게 추출 할 수 있습니다.

      • status 변수는 기본적으로 반복대상 오브젝트명 + "Stat" 변수명으로 접근 할 수 있으며

        th:each 선언시 개발자가 직접 명명하여 사용 할 수도 있습니다.

        index	현재 반복 인덱스  (0부터 시작)		
        count	현재 반복 인덱스  (1부터 시작)	
        size	총 요소 수
        current	현재 요소
        even	현재 반복이 짝수인지 여부 (boolean) 
        odd	현재 반복이 홀수인지 여부 (boolean)
        first	현재 반복이 첫번째인지 여부 (boolean) 
        last	현재 반복이 마지막인지 여부 (boolean)
        
        <!--/* <div th:each="num, numStat : ${#numbers.sequence(1,3)}"> */ -->
        <div th:each="num : ${#numbers.sequence(1,3)}">
        	<p th:text="${'index : ' + numStat.index}"></p>
        	<p th:text="${'count : ' + numStat.count}"></p>
        	<p th:text="${'size : ' + numStat.size}"></p>
        	<p th:text="${'current : ' + numStat.current}"></p>
        	<p th:text="${'even : ' + numStat.even}"></p>
        	<p th:text="${'odd : ' + numStat.odd}"></p>
        	<p th:text="${'first : ' + numStat.first}"></p>
        	<p th:text="${'last : ' + numStat.last}"></p>
        </div>
        
        ※ 위에 코드 실행시 결과
        <div>
        	<p>index : 0</p>
        	<p>count : 1</p>
        	<p>size : 3</p>
        	<p>current : 1</p>
        	<p>even : true</p>
        	<p>odd : false</p>
        	<p>first : true</p>
        	<p>last : false</p>
        </div>
        <div>
        	<p>index : 1</p>
        	<p>count : 2</p>
        	<p>size : 3</p>
        	<p>current : 2</p>
        	<p>even : false</p>
        	<p>odd : true</p>
        	<p>first : false</p>
        	<p>last : false</p>
        </div>
        <div>
        	<p>index : 2</p>
        	<p>count : 3</p>
        	<p>size : 3</p>
        	<p>current : 3</p>
        	<p>even : true</p>
        	<p>odd : false</p>
        	<p>first : false</p>
        	<p>last : true</p>
        </div>

5-4-2. 컬렉션 리스트 타입의 자바빈즈 프로퍼티 값을 반복하여 표시한다.

  • [요청] http://localhost:8080/ch0805/home0302

  • [컨트롤러 메서드]

    @GetMapping("ch0805/home0302")
    public String home0302(Model model) {
      Member member = new Member();
    
      List<String> hobbyList = new ArrayList<String>();
      hobbyList.add("Music");
      hobbyList.add("Movie");
    
      member.setHobbyList(hobbyList);
    
      model.addAttribute(member);
    
      return "ch0805/home0302";
    }
  • [뷰 화면]

    <html xmlns:th="http://www.thymeleaf.org">
    
    <head>
    	<title>Home</title>
    	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
    	<th:block th:each="hobby : ${member.hobbyList}">
    		<p th:text="${hobby}">hobby</p>
    	</th:block>
    </body>
    </html>
  • [응답 화면]

    5-4-3. 자바빈즈 컬렉션 리스트

  • 자바빈즈 컬렉션 리스트 요소를 가진 컬렉션 리스트 타입의 자바빈즈 프로퍼티 값을 반복하여 표시한다.

  • [요청] http://localhost:8080/ch0805/home0303

  • [컨트롤러 메서드]

    @GetMapping("ch0805/home0303")
    public String home0303(Model model) {
      Member member = new Member();
    
      List<Card> cardList = new ArrayList<Card>();
    
      Card card1 = new Card();
      card1.setNo("123456");
    
      YearMonth validMonth = YearMonth.of(2020, 9);
      card1.setValidMonth(validMonth);
    
      cardList.add(card1);
    
      Card card2 = new Card();
      card2.setNo("456786");
    
      YearMonth validMonth2 = YearMonth.of(2022, 11);
      card2.setValidMonth(validMonth2);
    
      cardList.add(card2);
    
      member.setCardList(cardList);;
    
      model.addAttribute(member);
    
      return "ch0805/home0303";
    }
  • [뷰 파일]

    <html xmlns:th="http://www.thymeleaf.org">
    
    <head>
    	<title>Home</title>
    	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </head>
    <body>
    	<th:block th:each="card : ${member.cardList}">
    		<span th:text="${card.no}">card.no</span>
    		<span th:text="${card.validMonth}">card.validMonth</span>
    		<br />
    	</th:block>
    	
    	<br />
    	
    	<th:block th:each="card : ${member.cardList}">
    		[[${card.no}]]
    		[[${card.validMonth}]]
    		<br />
    	</th:block>	
    </body>
    </html>
  • [응답 화면]

5-5. th:with

  • 타임리프는 th:with 속성을 사용하여 반복없이 지역 변수를 선언하는 방법을 제공한다.

    5-5-1.지역 변수

    • 지역 변수를 선언한 후 자바빈즈 프로퍼티 값을 그 지역 변수에 대입하여 사용한다.
    • [요청] http://localhost:8080/ch0805/home0402

    • [컨트롤러 메서드]

      @GetMapping("ch0805/home0402")
      public String home0402(Model model) {
        Member member = new Member();
      
        member.setUserId("hongkd");
      
        model.addAttribute(member);
      
        return "ch0805/home0402";
      }
    • [뷰 파일]

      <html xmlns:th="http://www.thymeleaf.org">
      
      <head>
      	<title>Home</title>
      	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
      </head>
      <body>
      	<table border="1" th:with="memberId=${member.userId}">
      		<tr>
      			<td>${member.userId}</td>
      			<td th:text="${memberId}">member.userId</td>
      		</tr>
      	</table> 
      </body>
      </html>
    • [응답 화면]

0개의 댓글