📚 Study/Thymeleaf

[Thymeleaf] 메시지, 변수, 객체

0_ch4n 2022. 7. 2. 02:39
반응형

 

✔️ 메시지

<!-- in HTML -->
<p th:utext="#{home.welcome}">Welcome to our grocery store!</p>
  • #{...} 라는 메시지 표현식을 사용하면 <p> 태그에 내용을 우리가 원하는 내용으로 대체할 수 있다.
<!-- home.properties -->
home.welcome=¡Bienvenido a nuestra tienda de comestibles!
  • home.welcome 에 대한 메시지는 properties 파일을 통해 관리된다.
<!-- in HTML -->
<p th:utext="#{home.welcome(${session.user.name})}">
  Welcome to our grocery store, Sebastian Pepper!
</p>

<!-- home.properties -->
home.welcome=¡Bienvenido a nuestra tienda de comestibles, {0}!
  • 만약 원하는 내용을 동적으로 처리하고 싶다면 ${...} 변수 표현식을 사용하면 된다.

 

📌 th:text 와 th:utext

<!-- in properties -->
home.welcome=Welcome to our <b>fantastic</b> grocery store!

<!-- Result -->
<p>Welcome to our &lt;b&gt;fantastic&lt;/b&gt; grocery store!</p>
  • 우리는 th:text를 사용하면 메시지로 HTML 태그를 표시하고 싶었지만 예상한 것과 다른 결과를 얻게 됩니다.
  • 이 때, < 나 > 같은 문자가 &lt; 나 &gt; 와 같은 문자로 바뀌는 것을 '이스케이프'라고 한다.
  • th:utext는 타임리프가 이스케이프 처리 하지 않도록 하는 속성이다.
<li>th:text 사용 <span th:text="${data}"></span></li>
<li>컨텐츠 안에서 직접 출력하기 = [[${data}]]</li>

<li>th:utext 사용 <span th:utext="${data}"></span></li>
<li>컨텐츠 안에서 직접 출력하기 = [(${data})]</li>
  • Escape
    • HTML 에서 <, > 같은 특수문자를 문자로 나타내는 것 = HTML 엔티티
    • th:text 나 [[…]] 를 사용한다
  • UnEscape
    • Escape 기능을 사용하지 않기 위한 방법
    • th:utext 나 [(…)]를 사용한다

✔️ 변수

<!-- in HTML -->
<p th:utext="#{home.welcome(${session.user.name})}">
  Welcome to our grocery store, Sebastian Pepper!
</p>

<!-- home.properties -->
home.welcome=¡Bienvenido a nuestra tienda de comestibles, {0}!
  • 우리는 위에서 이미 변수에 대해 알아봤다. ${...} 변수 표현식은 동적으로 렌더링 하기 위해 사용한다.
/* OGNL */

// point(.) 을 이용해 프로퍼티를 가져오는 방법
${person.father.name}

//대괄호[] 를 이용해 프로퍼티의 이름을 적어 프로퍼티를 가져오는 방법
${person['father']['name']}

//맵 객체인 경우 대괄호[]와 point(.)를 사용해 프로퍼티를 가져오는 방법
${countriesByCode.ES}
${personsByName['Stephen Zucchini'].age}

//컬렉션 객체인 경우 인덱스를 적어 프로퍼티를 가져오는 방법
${personsArray[0].name}

//메서드도 호출 가능하고 인자와 함께 호출도 가능하다
${person.createCompleteName()}
${person.createCompleteNameWithSeparator('-')}

/* SpringEL */

<h1>SpringEL 표현식</h1>
<ul>Object
    <li>${user.username} = <span th:text="${user.username}"></span></li>
    <li>${user['username']} = <span th:text="${user['username']}"></span></li>
    <li>${user.getUsername()} = <span th:text="${user.getUsername()}"></span></li>
</ul>
<ul>List
    <li>${users[0].username} = <span th:text="${users[0].username}"></span></li>
    <li>${users[0]['username']} = <span th:text="${users[0]['username']}"></span></li>
    <li>${users[0].getUsername()} = <span th:text="${users[0].getUsername()}"></span></li>
</ul>
<ul>Map
    <li>${userMap['userA'].username} = <span th:text="${userMap['userA'].username}"></span></li>
    <li>${userMap['userA']['username']} = <span th:text="${userMap['userA']['username']}"></span></li>
    <li>${userMap['userA'].getUserName()} = <span th:text="${userMap['userA'].getUsername()}"></span></li>
</ul>
  • 변수 표현식은 OGNL(Object-Graph Navigation Language) 표현식이고 스프링 MVC에선 SpringEL로 대체된다.

 

  • Object
    • user.username : user의 username에 프로퍼티 접근 ( = user.getUsername())
    • user[’username’] : 위와 같음.
    • user.getUsername() : 위와 같음. getUsername()을 직접 호출
  • List
    • users[0].username : user의 0번 인덱스 username에 프로퍼티 접근 (= list.get(0).getUsername())
    • users[0]['username'] : 위와 같음.
    • users[0].getUsername() : 위와 같음. getUsername()을 직접 호출
  • Map
    • userMap['userA'].username : Map에서 userA를 찾고 username에 프로퍼티 접근 (= map.get(”userA”).getUsername())
    • userMap['userA']['username'] : 위와 같음.
    • userMap['userA'].getUsername() : 위와 같음. getUsername()을 직접 호출

 

📌 선택 변수 - th:object , *{...}

<div th:object="${session.user}">
  <p>Name: <span th:text="*{firstName}">Sebastian</span>.</p>
  <p>Surname: <span th:text="*{lastName}">Pepper</span>.</p>
  <p>Nationality: <span th:text="*{nationality}">Saturn</span>.</p>
</div>
  • 부모 태그에 th:object를 사용해 객체를 선택하면 해당 태그 내에선 *{...} 선택 변수 표현식을 사용해 바로 접근할 수 있다.
  • 이 방법은 좀 더 편하게 사용할 수 있게 해주는 방법으로 th:object 태그 내에서 ${...} 표현식을 써도 상관없다.

 

📌 지역 변수 - th:with

<div th:with="first=${users[0]}">
	<p>처음 사람의 이름은 <span th:text="${first.username}"></span></p>
</div>
  • 사용할 태그 안에 th:with=”변수이름=값” 으로 선언해서 사용할 수 있다.
  • 선언한 태그 안에서만 사용할 수 있다.

✔️ 객체들

  • OGNL 표현식을 사용할 때 높은 유연성을 위해 표현식에 일부 객체를 사용할 수 있도록 제공한다.

 

📌 표현식 기본 객체

  • #ctx: 컨텍스트 객체.
  • #vars:컨텍스트 변수.
  • #locale: 컨텍스트 로케일.
  • #request: (웹 컨텍스트에서만) HttpServletRequest객체.
  • #response: (웹 컨텍스트에서만) HttpServletResponse객체.
  • #session: (웹 컨텍스트에서만) HttpSession객체.
  • #servletContext: (웹 컨텍스트에서만) ServletContext객체.

 

📌 표현식 유틸리티 객체

  • #execInfo: 처리 중인 템플릿에 대한 정보입니다.
  • #messages: #{…} 구문을 사용하여 얻을 수 있는 것과 같은 방식으로 변수 표현식 내에서 외부화된 메시지를 얻는 방법.
  • #uris: URL/URI의 일부를 이스케이프하는 방법
  • #conversions: 구성된 변환 서비스 를 실행하는 방법 (있는 경우).
  • #dates: 개체에 대한 메서드 java.util.Date: 서식 지정, 구성 요소 추출 등
  • #calendars: #dates와 유사하지만 java.util.Calendar객체용입니다.
  • #numbers: 숫자 개체의 서식을 지정하는 방법입니다.
  • #strings: 객체에 대한 메소드 String: 포함, startsWith, prepending/appending 등
  • #objects: 일반적으로 개체에 대한 메서드입니다.
  • #bools: 부울 평가 방법.
  • #arrays: 배열을 위한 메소드.
  • #lists: 목록에 대한 메소드.
  • #sets: 집합에 대한 메서드.
  • #maps: 지도를 위한 메소드.
  • #aggregates: 배열이나 컬렉션에 집계를 생성하는 방법.
  • #ids: 반복될 수 있는 id 속성을 처리하는 방법(예: 반복의 결과).

 

📌 편의 객체

  • ${param.XXX} : HTTP 요청 쿼리 파라미터 접근
  • ${session.XXX} : HTTP 세션 접근
  • ${@빈이름.메서드이름} : 스프링 빈 접근

 

📌 날짜 객체

<h1>LocalDateTime</h1>
<ul>
    <li>default = <span th:text="${localDateTime}"></span></li>
    <li>yyyy-MM-dd HH:mm:ss = <span th:text="${#temporals.format(localDateTime, 'yyyy-MM-dd HH:mm:ss')}"></span></li>
</ul>
<h1>LocalDateTime - Utils</h1>
<ul>
    <li>${#temporals.day(localDateTime)} = <span th:text="${#temporals.day(localDateTime)}"></span></li>
    <li>${#temporals.month(localDateTime)} = <span th:text="${#temporals.month(localDateTime)}"></span></li>
    <li>${#temporals.monthName(localDateTime)} = <span th:text="${#temporals.monthName(localDateTime)}"></span></li>
    <li>${#temporals.monthNameShort(localDateTime)} = <span th:text="${#temporals.monthNameShort(localDateTime)}"></span></li>
    <li>${#temporals.year(localDateTime)} = <span th:text="${#temporals.year(localDateTime)}"></span></li>
    <li>${#temporals.dayOfWeek(localDateTime)} = <span th:text="${#temporals.dayOfWeek(localDateTime)}"></span></li>
    <li>${#temporals.dayOfWeekName(localDateTime)} = <span th:text="${#temporals.dayOfWeekName(localDateTime)}"></span></li>
    <li>${#temporals.dayOfWeekNameShort(localDateTime)} = <span th:text="${#temporals.dayOfWeekNameShort(localDateTime)}"></span></li>
    <li>${#temporals.hour(localDateTime)} = <span th:text="${#temporals.hour(localDateTime)}"></span></li>
    <li>${#temporals.minute(localDateTime)} = <span th:text="${#temporals.minute(localDateTime)}"></span></li>
    <li>${#temporals.second(localDateTime)} = <span th:text="${#temporals.second(localDateTime)}"></span></li>
    <li>${#temporals.nanosecond(localDateTime)} = <span th:text="${#temporals.nanosecond(localDateTime)}"></span></li>
</ul>
  • ${localDateTime} : 현재 날짜와 시간을 표시
  • #temporals : JAVA 8의 날짜 서식을 지원

반응형