2006/11/21 10:45 Developer
freemarker 실전2 : Template 클래스
Template Class API
http://freemarker.sourceforge.net/docs/api/freemarker/template/Template.html
Configuration instance를 통해서 요렇게 얻어온다.
ex1)
ex2)
Merging the template with the data model
아주 심플하고 쉽다.
정리를 하자면, Configuration을 통해서 파일의 위치와 기타 정보를 셋팅 인스턴스를 만든 다음 템플릿 객체를 얻어와서 merging작업을 하면 끝!!
오래 기다렸다. 한방에 코드를 보자.
http://freemarker.sourceforge.net/docs/api/freemarker/template/Template.html
Configuration instance를 통해서 요렇게 얻어온다.
ex1)
Configuration cfg = new Configuration();
...
Template myTemplate = cfg.getTemplate("myTemplate.html");
...
Template myTemplate = cfg.getTemplate("myTemplate.html");
ex2)
|
Merging the template with the data model
|
아주 심플하고 쉽다.
정리를 하자면, 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로 이어서 만드는 객체들을 하나씩
제거하는 일만 남았다.
http://freemarker.sourceforge.net/docs/pgui_quickstart_all.html