简体   繁体   English

将freemarker模板写入String输出

[英]Write freemarker template to String output

I would like to have freemarker template output in String. 我想在String中有freemarker模板输出。 I have a freemarker template file commonTemplate.ftl . 我有一个freemarker模板文件commonTemplate.ftl

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

And Java code which populates model and prints output to console App.java . 和Java代码填充模型并将输出打印到控制台App.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;
    }
}

It works for console output. 它适用于控制台输出。

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

Hope this works. 希望这有效。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM