94일차_SpringBoot

서창민·2023년 7월 25일
0

SpringBoot

목록 보기
4/13
post-thumbnail

23.07.25 94일차

타임리프 게시판

  • Thymeleaf (타임리프)
타임리프는 컨트롤러를 타는 페이지만 먹는, 서버단에서 동작하는 프론트언어이다.
컨트롤러 탈 필요가 없는 단순한 html 페이지에서는 동작하지 않는다. 
자바스크립트까지 가지 않아도 html 에서 처리할 수 있는
간편하게 쓰일 수 있는 유용한 기능들이 많다. 

태그에 값 셋팅
<div th:text="${sports}"></div>

태그에 값 셋팅 (연산)
<span th:text="${sports}-1"></span>
<span th:text="${sports-1}"></span>

html 태그가 들어있는 텍스트를 태그로 삽입하고 싶을 때
<p th:utext="${sports}"></p>

문자열 합치기

<div th:text="'Hello, ' + ${name} + '!'"></div>
<div th:text="|Hello, ${name}!|"></div>

value 값 셋팅
<input type="hidden" th:value="${sports}"/>

==============================================

반복문

<ul th:each="sports : ${SPORTS}">
<li th:text="${sports['name']}"></li>
<li th:text="${sports['event']}"></li>
</ul>

ul 태그 안에 있는 것들이 반복된다 

if문

// 한 가지 조건
<span th:if="${sports['name'] != null}">

// and 나 or 조건 추가
<span th:if="${sports['name'] != null and sports['name'] != ''}">

if~else문
<span th:if="${sports['count'] != '1'}">
<span th:unless="${sports['count'] != '1'}">
주의할 점은 unless 문은 if문과 같은 조건을 써주어야 한다는 것이다.

switch case 문

<td th:switch="${join.gender}">
<span th:case="'M'" th:text="Male" /> 
<span th:case="'F'" th:text="Female" />
</td>

*주의 : 서로 다른 케이스별로 딱 한번씩만 적용이 됨.

====================================================

이미지 태그에 src 속성
<img th:src="${sports['pic']}" alt="" />

링크 url

// 기본적인 링크 삽입
<a th:href="@{/index}"/>

// 고정된 url과 변수를 함께 사용할 때
<a th:href="${'http://www.naver.com' + sports}" target="_blank">링크</a>

* 파라미터 값 여러개 넘기기 
<a th:href="@{/memberDelete.do(id=${m.id},password=${m.password})}">
		 [[${m.password}]]
</a>	 

// 링크에 파라미터를 보낼 때
<a th:href="@{/board/qna/modify?id=} + ${sports.id}">수정</a>

정리해서 보면 

@{ } 은 문자열을 그대로 url 로 쓰는 것이고
${ } 은 변수를 url 에 쓰는 것이다. 

=====================================

자바스크립트 안에서 타임리프 변수 사용

타임리프 변수에 [[ ]] 를 붙여준다.

// 변수 한 개

<a th:onclick="popUp( [[ ${sports['event']} ]] );"></a>
// 변수 여러 개
<li th:onclick="detailSports( [[ ${sports['code']} ]], [[ ${sports['name']} ]] );">

==============================================

변수 표기법

// 단일 변수 (String, Int 등)
${person}

// 속성값 접근
${person.father.name}

// 원소 접근
${person['father']['name']}
${personsByName['Stephen Zucchini'].age}
${personsArray[0].name}

// 메소드 접근
${person.createCompleteName()}
${person.createCompleteNameWithSeparator('-')}

. : string 속성값에 접근, 객체의 메소드 호출, 한 행이나 한 열로만 이루어져 있는 데이터 값에서 사용

[ ] : Map이나 Array의 원소에 접근

객체에 값이 비어있는지 확인
<li th:if="${#lists.isEmpty(SPORTS)}">

객체 건수 확인
<h4 th:text="${#lists.size(SPORTS)}"></h4>

문자열 자르기

#strings.arraySplit 로 문자열을 잘라 배열로 만들고 th:each 로 반복해서 뿌려준다.

<tr th:each="sports : ${#strings.arraySplit(str, ',')}">
<td th:text="${sports}"></td>
</tr>

구분자 두 개를 가지고 있는 문자열을 각 구분자로 모두 자르는 형태다. 

<li th:each="sports : ${#strings.arraySplit(str, '|')}">
<span th:text="${#strings.arraySplit(sports, '@')[0]}"></span>
<span th:text="${#strings.arraySplit(sports, '@')[1]}"></span>
</li>

| 로 구분되어 있는 걸 먼저 자르고 
@ 로 다시 자른 첫번째 값과 두번째 값을 가져오는 형태다. 
예를 들면 
str = "한국어@가@나 | 영어@A@B"; 
주의할 점은 자를 때는 해당 문자열이 null 이면 에러가 나기 때문에 사전에
 null 체크를 먼저 해주어야 한다.

==============================================================

태그 삭제
<li th:remove="tag"></li>

임의로 태그 생성
<th:block th:text="${sports.name}" />

include 기능
<th:block th:include="/header"/>


타임리프 사용 선언
<html lang="ko" xmlns:th="http://www.thymeleaf.org">

기본 사용에 대한 내용이다.

 +++++++++++++++++++++++++++

                   실 습 예 제 

 +++++++++++++++++++++++++++

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
  <h1 th:text="${greeting}" ></h1>
  <div th:with="userid='young' , userName='영원' ">
   
    화면에 값출력하기 1. :  [[ ${userid}  ]]  <br> <br>
    화면에 값출력하기 2. :  [[ ${userName}  ]]   
  
  </div>  

<hr>
 <!--  변수 선언  with  -->
 <div th:with="k1=100 , k2=200">
  연산하기 :  [[ ${k1 + k2} ]] 
 </div>  
 
 <!--  태그안에 글 작성하기 ( 작은따옴표 필수 ) -->
 <span style="background-color: rgb(255,0,0);" th:text="'hello 출   력'"> </span>
 <div style="background-color: rgb(0,255,0);" th:text="'hello 출   력'"> </div>
 <p style="background-color: rgb(255,255,0);" th:text="'hello 출   력'"> </p>
 
  <!--  변수 선언  with  -->
 <div th:with="str1='kor' , str2='eng'">
  연산하기 :  [[ '국 어:' + ${str1} + ', 영 어:' + ${str2}  ]] 
 </div>
 
 <!--  문자열 합치기  -->  
 <div th:with="str1='kor' , str2='eng'">
     확인1: <span th:text="'국 어:' + ${str1} + ', 영 어:' + ${str2}" ></span> <br>
     확인2: <span th:text="|국 어: ${str1} , 영 어: ${str2}|" ></span>
 </div> 
 
</body>
</html>

기본 사용을 실제 HTML 파일에서 사용하는 방법과, 예시이다.

profile
Back-end Developer Preparation Students

1개의 댓글

comment-user-thumbnail
2023년 7월 25일

좋은 정보 감사합니다

답글 달기