[Thymeleaf] 문법

Ogu·2023년 5월 2일
0

SpringBoot

목록 보기
10/17

3. Using Texts

th태그를 이용해서 적용

  • @ : link를 나타내는 타임리프의 키워드
    실제 html 문서를 열었을때는 href="../../css/gtvg.css"가 적용되지만, 서버 구동시에는 th:href="@{/css/gtvg.css}가 적용됩니다
<link rel="stylesheet" type="text/css" media="all" 
          href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
  • # : 타임리프에서 제공하는 메시지를 나타내는 키워드입니다. home.welcome이라고 정의되어있는 메시지를 다국어를 지원한다면, home.welcomd에 해당하는 값을 해당 언어 버전으로 스트링 부트에서 설정할 수 있습니다.

공식 doc
https://www.thymeleaf.org/doc/tutorials/3.1/usingthymeleaf.html#using-texts

Unescaped Text

Thymeleaf가 HTML 태그를 따르고 이스케이프하지 않도록 하려면 다른 속성을 사용해야 한다. th:utext("이스케이프 처리되지 않은 텍스트"용):
태그안에 또 태그를 사용하고 싶을때는 utext를 이용한다.

4 Standard Expression Syntax

Controller에서 넘겨준 값으로 대체하기 위해서는 다음과 같이 사용합니다.

<p th:utext="#{home.welcome}">Welcome to our grocery store!</p>

<p>Today is: <span th:text="${today}">13 february 2011</span></p>
  • Simple expressions:
    • Variable Expressions: ${...}
    • Selection Variable Expressions: *{...}
    • Message Expressions: #{...} (다국어 지원)
    • Link URL Expressions: @{...}
    • Fragment Expressions: ~{...} (화면별로 공통적인 화면이 있을 경우 대표 화면을 지정해서 불러올 수 있음 -> 공통된 작업 시작 단축)
  • Literals
    • Text literals: 'one text', 'Another one!',…
    • Number literals: 0, 34, 3.0, 12.3,…
    • Boolean literals: true, false
    • Null literal: null
    • Literal tokens: one, sometext, main,…
  • Text operations:
    • String concatenation: +
    • Literal substitutions: |The name is ${name}|
  • Arithmetic operations:
    • Binary operators: +, -, *, /, %
    • Minus sign (unary operator): -
  • Boolean operations:
    • Binary operators: and, or
    • Boolean negation (unary operator): !, not
  • Comparisons and equality:
    • Comparators: >, <, >=, <= (gt, lt, ge, le)
    • Equality operators: ==, != (eq, ne)
  • Conditional operators:
    • If-then: (if) ? (then)
    • If-then-else: (if) ? (then) : (else)
    • Default: (value) ?: (defaultvalue)
  • Special tokens:
    • No-Operation: _

4.1 Messages

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

4.2 Valuables

Expression Utility Objects

Expression Utility Objects

Besides these basic objects, Thymeleaf will offer us a set of utility objects that will help us perform common tasks in our expressions.

  • execInfo: information about the template being processed.
  • messages: methods for obtaining externalized messages inside variables expressions, in the same way as they would be obtained using #{…} syntax.
  • uris: methods for escaping parts of URLs/URIs
  • conversions: methods for executing the configured conversion service (if any).
  • dates: methods for java.util.Date objects: formatting, component extraction, etc.
  • calendars: analogous to #dates, but for java.util.Calendar objects.
  • temporals: for dealing with dates and times using the java.time API in JDK8+.
  • numbers: methods for formatting numeric objects.
  • strings: methods for String objects: contains, startsWith, prepending/appending, etc.
  • objects: methods for objects in general.
  • bools: methods for boolean evaluation.
  • arrays: methods for arrays.
  • lists: methods for lists.
  • sets: methods for sets.
  • maps: methods for maps.
  • aggregates: methods for creating aggregates on arrays or collections.
  • ids: methods for dealing with id attributes that might be repeated (for example, as a result of an iteration).
    You can check what functions are offered by each of these utility objects in the Appendix B.

4.3 Expressions on selections (asterisk syntax)

  <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="${session.user}" 를 통해 object를 지정하면 *{firstName}와 같이 user.firstName으로 지정하지 않아도 됩니다.

4.8 Literal substitutions

리터럴 대체를 사용하면 '...' + '...'로 리터럴을 추가할 필요 없이 변수의 값을 포함하는 문자열의 형식을 쉽게 지정할 수 있습니다. 이러한 대체 항목은 다음과 같이 세로 막대|로 둘러싸야 합니다.

<span th:text="|Welcome to our application, ${user.name}!|">

위의 |로 감싼 문자열은 다음과 같습니다.

<span th:text="'Welcome to our application, ' + ${user.name} + '!'">

또한 다른 유형의 표현식과 결합할 수 있습니다.

<span th:text="${onevar} + ' ' + |${twovar}, ${threevar}|">

5 Setting Attribute Values

5.1 Setting the value of any attribute

<form action="subscribe.html" th:attr="action=@{/subscribe}">
  <fieldset>
    <input type="text" name="email" />
    <input type="submit" value="Subscribe!" th:attr="value=#{subscribe.submit}"/>
  </fieldset>
</form>

5.2 Setting value to specific attributes

<form action="subscribe.html" th:action="@{/subscribe}">

Template layout

8.1 Including template fragments

반복되는 요소를 밖에서 가져올 수 있다.

INF/templates/footer.html 파일이 아래와 같을때

<!DOCTYPE html>

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

  <body>
  
    <div th:fragment="copy">
      &copy; 2011 The Good Thymes Virtual Grocery
    </div>
  
  </body>
  
</html>

아래와 같이 사용할 수 있다.

<body>

  ...

  <div th:insert="~{footer :: copy}"></div>
  
</body>

intser와 replace의 차이점은 다음 과 같다.

  • th:insert : will simply insert the specified fragment as the body of its host tag.

  • th:replace : actually replaces its host tag with the specified fragment.

아래 푸터가 다음과 같이 있을 때,

<footer th:fragment="copy">
  &copy; 2011 The Good Thymes Virtual Grocery
</footer>

다음과 같이 insert, repalce를 통해 가져와보자.

<body>

  ...

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

  <div th:replace="~{footer :: copy}"></div>
  
</body>

결과는 다음과 같이 나타난다.

<body>

  ...

  <div>
    <footer>
      &copy; 2011 The Good Thymes Virtual Grocery
    </footer>
  </div>

  <footer>
    &copy; 2011 The Good Thymes Virtual Grocery
  </footer>
  
</body>

9. Local Variables

10. Attribute Precedence

속성 우선순위는 다음과 같다.

11. Comments and Blocks

11.2. Thymeleaf parser-level comment blocks

<!--/*--> <!--*/--> 사이의 코드는 샘플 데이터로, 서버 구동 시에는 보이지 않는다.

<table>
   <tr th:each="x : ${xs}">
     ...
   </tr>
   <!--/*-->
   <tr>
     ...
   </tr>
   <tr>
     ...
   </tr>
   <!--*/-->
</table>

11.3. Thymeleaf prototype-only comment blocks

반대로, 아래 <!--/*/ ~ /*/--> 안에 있는 것들은 파일을 열었을 때는 보이지 않지만, 실제 서버 구동시에는 나타나게 된다.

<span>hello!</span>
<!--/*/
  <div th:text="${...}">
    ...
  </div>
/*/-->
<span>goodbye!</span>
<span>hello!</span>
 
  <div th:text="${...}">
    ...
  </div>
 
<span>goodbye!</span>

11.4. Synthetic th:block tag

th:block 인 속성은 실제 반영은 되지만 서버 구동시에는 보이지 않는다.
태그 없이 서버의 데이터를 사용하고 싶을 때 사용한다.

<table>
  <th:block th:each="user : ${users}">
    <tr>
        <td th:text="${user.login}">...</td>
        <td th:text="${user.name}">...</td>
    </tr>
    <tr>
        <td colspan="2" th:text="${user.address}">...</td>
    </tr>
  </th:block>
</table>

Inlining

12.1 Expression inlining

아래 두 문장은 같은 기능을 한다.

[[]]th:text 속성을 대신한다.

<p>Hello, [[${session.user.name}]]!</p>
<p>Hello, <span th:text="${session.user.name}">Sebastian</span>!</p>

[(...)]th:utest 속성을 대신한다.

다음 문장의 결과는

<p>The message is "[(${msg})]"</p>

아래와 같이 나타난다.

<p>The message is "This is <b>great!</b>"</p>

12.3 JavaScript inlining

script의 inline 속성을 javascript 로 지정한다.

<script th:inline="javascript">
    ...
    var username = [[${session.user.name}]];
    ...
</script>
profile
私はゲームと日本が好きなBackend Developer志望生のOguです🐤🐤

0개의 댓글