> Hello World !!!

     

@syaku

프리마커 템플릿 소스 불러오기 : freemarker ftl


written by Seok Kyun. Choi. 최석균

"프리마커 템플릿 소스 불러오기"

프리마커에서 템플릿 소스를 호출하여 임의적으로 수정하고 문자열로 반환하는 방법을 포스팅하였다.

예를들면 A 라는 페이지에 B라는 페이지를 내용을 삽입하고자 할때 사용하면 된다.


템플릿 소스를 절대경로로 호출하여 내용에 삽입되는 데이터를 넣고 결과를 문자열로 받을 수 있다.


+ 자바 클래스

/*
 * TemplateUtils.java 2011.08.04
 *
 * Copyright (c) 2010, MEI By Seok Kyun. Choi. (최석균)
 * http://syaku.tistory.com
 * 
 * GNU Lesser General Public License
 * http://www.gnu.org/licenses/lgpl.html
 */

 package com.syaku.core.util;

import java.util.*;
import java.io.*;

import org.apache.log4j.Logger;
import org.apache.commons.lang.*;

import freemarker.template.*;

public class TemplateUtils {
  private static Logger log = Logger.getLogger(TemplateUtils.class);

  public static String getString(String dir,String file,Map map) throws Exception {
    return getString(dir,file,map,"utf-8"); // 캐릭터셋 지정
  }
  public static String getString(String dir,String file,Map map,String charset) throws Exception {
    charset = StringUtils.defaultIfEmpty(charset,"utf-8");
    String content = "";

    try{
      Configuration cfg = new Configuration();

      cfg.setDirectoryForTemplateLoading(new File(dir));
      cfg.setObjectWrapper(new DefaultObjectWrapper());
      cfg.setDefaultEncoding(charset);
      cfg.setEncoding(Locale.KOREAN, charset);

      Template temp = cfg.getTemplate(file);
      ByteArrayOutputStream os = new ByteArrayOutputStream();
      Writer output = new OutputStreamWriter(os, charset);

      try {
        temp.process(map, output);
      } catch (TemplateException e) {
        e.printStackTrace();
      }

      output.flush();
      output.close();
      os.close();
      map.clear();

      content = os.toString(charset);
      log.debug(content); // 로그 출력
    }catch (Exception e) {
      log.error(e.toString()); // 로그 출력
    }

    return content;

  }

}


+ 예제 HTML (FTL) 템플릿 소스 : D:/syaku/ftl/html.ftl

<p>${name} 입니다?</p> 이런 소스가 있다고 가정함.


+ 예제 템플릿 호출

Map data = new HashMap();

data.put("name" , "샤쿠");


// 템플릿 절대경로 폴더 , 템플릿 파일명 , 데이터

String source = TemplateUtils.getString( "D:/syaku/ftl" , "html.ftl" , data );



posted syaku blog

Syaku Blog by Seok Kyun. Choi. 최석균.

http://syaku.tistory.com