1

I am new to freemarker. I have a spring application that I am planning to use with freemarker. Templates will be stored in database and based on the login, I want to retrieve the template from database. Can any one tell me how to configure the freemarker in spring and get the html tags as a string after constructing the template. I did googling but I could not understand much.

I tried till this level. In spring I have done till this level. Finally I want html tags in a string.

// Spring freemarker specific code
Configuration configuration = freemarkerConfig.getConfiguration();
StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
// My application specific code
String temp = tempLoader.getTemplateForCurrentLogin();

Thanks.

4

2 回答 2

2

要将您发布的代码位捆绑在一起,您可以执行以下操作:

// you already have this bit
String templateText = tempLoader.getTemplateForCurrentLogin();

// now programmatically instantiate a template
Template t = new Template("t", new StringReader(templateText), new Configuration());

// now use the Spring utility class to process it into a string
// myData is your data model
String output = FreeMarkerTemplateUtils.processTemplateIntoString(template, myData);
于 2010-02-15T06:35:11.370 回答
1

该 java 方法将处理 freemarker 模板,并在构建模板后将 html 标签作为字符串。

public static String  processFreemarkerTemplate(String fileName) {

        StringWriter stringWriter = new StringWriter();
        Map<String, Object> objectMap = new HashMap<>();
        Configuration cfg = new Configuration(Configuration.VERSION_2_3_24);

        try {
            cfg.setDirectoryForTemplateLoading(new File("path/of/freemarker/template"));
            cfg.setDefaultEncoding("UTF-8");
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            cfg.setLogTemplateExceptions(false);

            Template template = cfg.getTemplate(fileName);
            template.process(objectMap, stringWriter);

        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        } finally {
            if (stringWriter != null) {
                try {
                    stringWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return stringWriter.toString();
    }
于 2020-01-08T09:37:53.307 回答