Configuration cfg = new Configuration(); ... Template myTemplate = cfg.getTemplate("myTemplate.html");
ex2)
Template temp = cfg.getTemplate("test.ftl");
Merging the template with the data model
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
out.flush();
아주 심플하고 쉽다.
정리를 하자면, Configuration을 통해서 파일의 위치와 기타 정보를 셋팅 인스턴스를 만든 다음 템플릿 객체를 얻어와서 merging작업을 하면 끝!!
오래 기다렸다. 한방에 코드를 보자.
import freemarker.template.*;
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) throws Exception {
/* ------------------------------------------------------------------- */
/* You usually do it only once in the whole application life-cycle: */
/* Create and adjust the configuration */
Configuration cfg = new Configuration();
cfg.setDirectoryForTemplateLoading(
new File("/where/you/store/templates"));
cfg.setObjectWrapper(new DefaultObjectWrapper());
/* ------------------------------------------------------------------- */
/* You usually do these for many times in the application life-cycle: */
/* Get or create a template */
Template temp = cfg.getTemplate("test.ftl");
/* Create a data model */
Map root = new HashMap();
root.put("user", "Big Joe");
Map latest = new HashMap();
root.put("latestProduct", latest);
latest.put("url", "products/greenmouse.html");
latest.put("name", "green mouse");
/* Merge data model with template */
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
out.flush();
}
}
다음과 같은 코드면 쉽게 템플릿 엔진을 사용할 수가 있다. 좀더 드는 공수는 FTL을 학습하는 것이지만, 학습곡선이 길지가 않을 것이다.
자바 속에 들어있는 HTML관련해서 String or StringBuffer로 이어서 만드는 객체들을 하나씩 제거하는 일만 남았다.
Configuration cfg = new Configuration();
// Specify the data source where the template files come from.
// Here I set a file directory for it:
cfg.setDirectoryForTemplateLoading(
new File("/where/you/store/templates"));
// Specify how templates will see the data model. This is an advanced topic...
// but just use this:
cfg.setObjectWrapper(new DefaultObjectWrapper());
과거에는 velocity가 주로 템플릿 엔진으로 사용이 됐는데, 최근에는 webwork와 함께 FreeMarker가 주목을 많이 받고 있는듯 하다.
What is FreeMarker?
FreeMarker is a "template engine"; a generic tool to generate text output (anything from HTML to autogenerated source code) based on templates. It's a Java package, a class library for Java programmers. It's not an application for end-users in itself, but something that programmers can embed into their products.
Template + data model = output
Ubiquitous Language : 용어정리를 해보자 - We say that the output is created by merging a template and a data model - Files like this are called templates.
<p>We have these animals:
<table border=1>
<tr><th>Name<th>Price
<#list animals as being>
<tr>
<td>
<#if being.size = "large"><b></#if>
${being.name}
<#if being.size = "large"></b></#if>
<td>${being.price} Euros
</#list>
</table>
ouput을 만들기 위한 샘플코드
public String createTemplateContents(String fileName, Object root) throws Exception { final Writer out = new StringWriter(); Configuration cfg = new Configuration(); cfg.setClassicCompatible(false); cfg.setClassForTemplateLoading(getClass(), THEME_TEMPLATES_CLASSPATH); cfg.setObjectWrapper(new DefaultObjectWrapper()); Template temp = cfg.getTemplate(fileName); temp.process(root, out); out.flush(); return out.toString(); }
기타
(열심히 API학습중!)
오~ freemarker쓸만한데, TemplateModel 인터페이스는 감동이었다. 이거 잘 이용하면 DTO형태의 Proxy클래스를 만들지 않아도 되겠다.
Velocity에도 이런 기능이 있었을 텐데, 그땐 웹UI로만 사용을 해서 깊이 있게 못 봤는데, 앞으로 template engine은 freemarker를 사용하면서 좀더 깊이 있게 들여다 봐야 겠군.
일단 소기의 목적을 달성을 위한 만큼의 API공부는 달성!!
잘 만든 Domain Model클래스를 이용하여, 타입이 확실한 형태의 도메인 모델을 이용한 코드를 만들수도 있다. 그건 차후에 샘플을 올리도록 하겠다. 매번 property의 이름을 찾아서 Map에 담는 형태보다는 사전에 정의된 Bean을 이용하면 intuitable populate가 가능하다.