배경
Mustache 라는 템플릿 엔진을 사용하는 Spring Boot 기반의 프로젝트 투입이 예상 되어 기술 선행
학습 겸 글을 작성해봅니다.
Mustache는 JSP, Velocity, Freemarker, Thymleaf 등의 템플릿 엔진의 한종류로 보면되고
Thymleaf을 제외한 나머지 템플릿 엔진들은 스프링 부트에서 권장하지 않거나 많은 처리 기능이
지원되므로 자기도 모르게(아니면 의도적으로) 화면에 비즈니스 로직을 작성이 가능하다.
많은 템플릿 엔진 중에 왜 Mustache 만에 장점이 무엇인지 찾아보면 View 역할이 충실하기
위해 비즈니스 로직 작성이 제한적이면 다른 엔진들보다는 비교적 문법이 쉽다고 하는데
솔직히 예제를 작성해보면서 크게 문법 난이도는 체감 하지 못했다.
환경 설정
IDE는 인텔리제이 커뮤니티 버전 기준으로 설정 진행.
1. Spring Boot 생성 및 다운로드
start.sping.io에서 프로젝트 생성 및 다운로드
의존성은 간단하게 테스트 API와 화면 출력 정도로 구성하므로 이미지의 2개만 추가.
2. 인텔리제이 프로젝트 Import
import 완료 후 build.gradle 파일을 열어보면 의존성에 아래와 같이 추가된 것을
확인할 수 있습니다.
3. Mustache 한글 encdoing 추가
application.propeties 파일에 추가해줍니다.
server.servlet.encoding.force-response=true
Demo API 작성
단건 조회, 목록 조회가 가능한 간단한 데모 API 작성.
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import java.util.*;
@Controller
public class TestController {
@GetMapping("/test")
public String getTest(Model model) {
model.addAttribute("info", "testInfo");
return "test";
}
@GetMapping("/test/list")
public String getTestList(Model model) {
Map<String, Object> map1 = new HashMap<>();
map1.put("id", 1);
Map<String, Object> map2 = new HashMap<>();
map2.put("id", 2);
Map<String, Object> map3 = new HashMap<>();
map2.put("id", null);
List<Map<String, Object>> list = new ArrayList<>();
list.add(map1);
list.add(map2);
list.add(map3);
model.addAttribute("infoList", list);
return "test-list";
}
}
Java
복사
Mustache Template 작성
두 API를 호출하면 각각에 값들이 정상 출력되는 것을 확인 가능하다.
Mustache는 JSTL 처럼 if문 case 문 같은 전통적인 조건문, 반복문은 지원하지 않고
아래와 같이 2번예제 같이 목록과 빈 값에 대한 분기 처리를 하기 위한 유사한 문법이 존재하기는
한다. 이렇게 간단한 반복 같은 처리 외에는 View만 출력하게 작성 하는 방식으로 사용이 가능할 것 같다.
1. /test
{{key}} 값을 작성하면 해당 값을 출력.
<!DOCTYPE HTML>
<html>
<head>
<title>Mustache Demo</title>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8"/>
</head>
<body>
<h1>Mustache Demo</h1>
{{info}}
</body>
</html>
HTML
복사
2. /test/list
{{#list}} {{key}} {{/list}} 값을 작성하면 목록 값을 출력.
<!DOCTYPE HTML>
<html>
<head>
<title>Mustache Demo</title>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8"/>
</head>
<body>
<h1>Mustache Demo</h1>
<table class="table table-horizontal table-bordered">
<thead class="thead-strong">
<tr>
<th>번호</th>
</tr>
</thead>
<tbody id="tbody">
{{#infoList}}
<tr>
<td>{{#id}} {{id}} {{/id}} {{^id}}빈값{{/id}}</td>
</tr>
{{/infoList}}
</tbody>
</table>
</body>
</html>
HTML
복사