【问题标题】:Write freemarker template to String output将 freemarker 模板写入字符串输出
【发布时间】:2017-06-18 01:13:13
【问题描述】:

我想在字符串中输出 freemarker 模板。 我有一个 freemarker 模板文件 commonTemplate.ftl.

<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>

【问题讨论】:

    标签: java freemarker


    【解决方案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);
        }
    

    【讨论】:

    • @Aman :你应该举个例子,解释一下你在什么上下文中看到'?'
    【解决方案2】:

    希望这行得通。

    // 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();
    

    【讨论】:

    • 如果数据中包含需要UTF-8编码的特殊字符怎么办?在这种情况下,结果将包含“?”人物。我们该如何解决这个问题?
    • 我猜你可以在配置对象中设置UTF设置。
    猜你喜欢
    • 2011-05-03
    • 2015-04-26
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-11
    • 1970-01-01
    • 2015-11-29
    相关资源
    最近更新 更多