[Thymeleaf] 타임리프 - 기본문법1

Harry park·2022년 6월 7일
0

Thymeleaf

목록 보기
2/3
post-thumbnail

📌 타임리프(Thymeleaf) 기본 문법1

📖 1) 설정

네임스페이스(Namespace) 추가

📎 xmlns:th=" "

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

✍ 순수한 HTML으로만 작성된 페이지에는 선언하지 않아도 된다.
th속성을 사용하기 위한 네임스페이스

📖 2) 기능

✍ 2-1) 기본 기능

💻 표현식

  • 변수 : ${…}
  • 선택 변수 : *{…}
  • 메시지 : #{…}
  • Link URL : @{…}
    💻 비교연산
  • if-then : (if) ? (then)
  • if-then-else : (if) ? (then) : (else)
  • Default : (value) ?: (defaultValue)
    💻 text opeation
  • 문자열 연결 : +
  • 문자 대체 : |The name is ${name}|

✍ Spring EL

📎 Object

객체명 : user

💻 ${user.username}
Java Bean Property 접근 방법
💻 ${user['username']
Object에 직접 접근하여 해당 객체를 사용
💻 ${user.getUsername()}
setter/getter 중 getter 사용

📎 List

💻 {user[0].username}list.get(0).getUsername()
💻 ${user[0]['username']}
💻 ${user[0].getUsername}

📎 Map

💻 ${userMap['userA'].username}map.get("userA").getUsername()
💻 ${userMap['userA']['username']}
💻 ${userMap['userA'].getUsername()}

cf) 🎈HTML에서 제공하는 대표적인 엔티티

엔티티 문자 엔티티 이름 설명
&nbsp; 줄 바꿈 없는 공백
< &lt; 보다 작은
> &gt; 보다 큰
& &amp; AND 기호
" &quot; 큰따옴표
' &apos; 작은따옴표

✍ href

📖 <a></a> 태그의 href속성과 동일하다.

📎 th:href="@{}"

<a th:hrf="@{/write?id={id}}"></a>

✍ with

📖 변수 형태의 값을 재정의하는 속성.

📎 th:with="${}"

<div th:with="replaceObj=${users[0]}">
 	<p> replaceObj : <span th:text="${replaceObj.username}"></span></p>
</div>

cf) 🎈타임리프에선 지역 변수를 th:with사용을 통해 지원해준다. 단, 선언한 태그 내에서만 사용 가능하다.

✍ 텍스트 출력 : text, utext

  • text : 텍스트 출력
<li>th:text 사용 <span th:text="${data}">static text</span></li>
  • utext : bold 텍스트로 출력
<li>th:utext 사용 <span th:utext="${data}">static text</span></li>

✍ value

📖 <input />태그의 value에 값을 삽입할 때 사용하며, 값이 여러개 일 때는 + 기호(text operation)를 사용한다.

📎 th:value="${}"

<input type="text" id="username" 
       th:value="${userId} + '의 이름은 ${username}"/>

✍ th:placeholder

📖 <input />태그의 placeholer 내용 삽입에 사용

📎 th:placeholder="${}"

<input type="text" id="username" 
       th:placeholder="${usernamePlaceholder}"/>

✍ 2-2) Layout

📖 네임스페이스에 xmlns:layout="", layout:decorator="" 추가

📎 xmlns:layout="", layout:decorator=""

💻 예시

<html lang="ko" xmlns:th="http://www.thymeleaf.org" 
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{board/layout/basic}">

👉 의존성

// 코드중략
dependencies {
  	// 코드중략
	implementation 'nz.net.ultraq.thymeleaf:thymeleaf-layout-dialect'
    // 코드중략
}
// 코드중략
  • xmlns:layout은 타임리프의 레이아웃 기능을 사용하기 위한 선언이다.
  • 해당 페이지에 th:fagment로 조각한 공통 영역을 가져와서 삽입한다.

✍ th:block

📖 타임리프 구문을 어느 곳에서든 사용할 수 있도록 해주는 속성
📖 주로 동적인 처리를 요할 때 사용된다.(layout, switch 구문)

💻 예시

<html lagn="ko" 
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout">
<body>
  	// 코드 중략
	<th:block th:fragment="fragmentFooter">
 	</th:block>
</body>  
  
</html>

✍ th:fragment=""

📖 메뉴 영역이나 네비게이션과 같이 공통으로 반복되는 영역을 조각화 하기위한 속성이다.
📖 th:replace"[파일경로 :: 조각 이름]"로 사용한다.

✍ th:replace="~{파일경로 :: 조각이름}"

📖 jsp include와 비슷한 속성으로, fragment로 조각한 영역을 삽입(대치)하는 기능
cf) 🎈 insert와 유사한 기능이지만, replace는 완전하게 대체한다.
💻 예시

<footer th:fragment="footerFragment">
  <p>안녕하세요</p>
</footer>

✍ th:insert="~{파일경로 :: 조각이름}"

📖 insert는 태그 내로 조각을 삽입하는 방법이다.

<div th:insert="~{/common/footer :: fragmentFooter}"></div>  

form, 조건문, 반복문 그리고 기본 객체는 다음 게시글에 이어 작성하도록 하겠습니다.


개인적으로 공부하며 기록한 내용으로, 틀린 내용이 있는 경우 덧글을 달아주시면 감사하겠습니다. 😍

profile
Jr. Backend Engineer

0개의 댓글