[기술 정리] 13. Mustache 문법

KangHo Lee's avatar
Nov 29, 2024
[기술 정리] 13. Mustache 문법
💡
Mustache 템플릿 엔진은 간단하고 직관적인 문법을 사용하여 데이터를 템플릿에 삽입합니다.

1. 변수(Variables)

변수는 데이터의 값을 템플릿에 삽입하는 데 사용됩니다.
<h1>{{title}}</h1> <p>{{description}}</p>

2. HTML 이스케이프(HTML Escaping)

기본적으로 Mustache는 HTML을 이스케이프 처리하여 XSS 공격을 방지합니다.
html
<p>{{safeHtml}}</p>
데이터
// json data { "safeHtml": "<script>alert('hello');</script>" }
출력
<p>&lt;script&gt;alert('hello');&lt;/script&gt;</p>

3. 섹션(Sections)

조건부로 콘텐츠를 표시하거나 반복하려면 섹션을 사용합니다.

조건부 섹션

{{#isVisible}} <p>This will be shown if isVisible is true.</p> {{/isVisible}}
  • isVisible true일 때 p 태그 출력

null 조건

<!-- sessionUser가 null이 아니면 출력 --> {{#sessionUser}} <h1>세션에 저장된 유저 이름: {{sessionUser.username}} 세션에 저장된 정보 노출 주의</h1> {{/sessionUser}} <!-- sessionUser가 null 이면 출력 --> {{^sessionUser}} <h1>로그인되지 않은 상태입니다. 로그인해주세요.</h1> {{/sessionUser}}

반복 섹션

<ul> {{#items}} <li>{{name}}</li> {{/items}} </ul>

4. 주석(Comments)

주석을 사용하여 템플릿에 주석을 추가할 수 있습니다. 이는 출력에 영향을 미치지 않습니다.
{{! This is a comment }}

5. 파셜(Partials)

파셜을 사용하여 템플릿을 재사용(include)할 수 있습니다.
<h1>{{title}}</h1> {{> user}}
  • user.mustache 를 재사용

6. 현재 요소 반환

<section> {{#list}} <p>{{.}}</p> {{/list}} </section>
  • list가 ArrayList<String>일 경우 문자열이 하나씩 출력됩니다.

7. 리스트 출력

{{#boardList}} <tr> <td>{{id}}</td> <td>{{title}}</td> <td><a href="/board/{{id}}">상세보기</a></td> </tr> {{/boardList}}
 
Share article

devleekangho