2017-02-01 9 views
2

私はfreemarkerテンプレートの出力をStringにしたいと思っています。 freemarkerテンプレートファイルcommonTemplate.ftlがあります。freemarkerテンプレートを文字列出力に書き込む

<div> 
    <div> 
     <h1>${userDetails.name}</h1> 
     ${userDetails.birthday} ${userDetails.id} 
    </div> 
</div> 

そしてApp.javaコンソールするためのモデルと印刷出力を移入するJavaコード。

public class App { 

    private Service service = new Service(); 


    public void execute() { 
     Configuration configuration = prepareConfiguration(); 
     // Load templates from resources/templatess. 
     configuration.setClassForTemplateLoading(App.class, "/templates"); 

     try { 
      Template template = configuration.getTemplate("commonTemplate.ftl"); 

      // Console output 
      Writer out = new OutputStreamWriter(System.out); 
      template.process(prepareData(), out); 
      out.flush(); 

     } catch (IOException | TemplateException e) { 
      throw new RuntimeException(e); 
     } 
    } 

    private Configuration prepareConfiguration() { 
     Configuration configuration = new Configuration(Configuration.VERSION_2_3_23); 
     configuration.setDefaultEncoding("UTF-8"); 
     configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); 
     configuration.setLogTemplateExceptions(false); 
     return configuration; 
    } 

    private Map<String, Object> prepareData() { 
     Model model = service.getModel(); 
     Map<String, Object> data = new HashMap<String, Object>(); 
     data.put("userDetails", model.getUserDetails()); 
     return data; 
    } 
} 

コンソール出力用です。

<div> 
    <div> 
     <h1>john Doe</h1> 
     1990-01-10T12:11+01:00[Europe/Prague] 1 
    </div> 
</div> 

答えて

8

この作品を願っています。

// write the freemarker output to a StringWriter 
StringWriter stringWriter = new StringWriter(); 
template.process(prepareData(), stringWriter); 

// get the String from the StringWriter 
String string = stringWriter.toString(); 
+0

はい、それは、ありがとう、働いています。 –

+0

データにUTF-8エンコーディングが必要な特殊文字が含まれる場合はどうなりますか?その場合、結果に '?'が含まれます。文字。どうすればこの問題を解決できますか? – Aman

1
try { 
     Template template = configuration.getTemplate("commonTemplate.ftl"); 
     Writer out = new StringWriter(); 
     template.process(prepareData(), out); 
     System.out.println(out.toString()); 

    } catch (IOException | TemplateException e) { 
     throw new RuntimeException(e); 
    } 
+0

データにUTF-8エンコーディングが必要な特殊文字が含まれている場合はどうなりますか?その場合、結果に '?'が含まれます。文字。どうすればこの問題を解決できますか? – Aman

関連する問題