代码之家  ›  专栏  ›  技术社区  ›  DonX

使用freemarker和spring构造模板

  •  0
  • DonX  · 技术社区  · 15 年前

    我对freemarker不熟悉。我有一个spring应用程序,我计划与freemarker一起使用。模板将存储在数据库中,并根据登录,我想从数据库检索模板。有谁能告诉我如何在spring中配置freemarker,并在构建模板之后将html标记作为字符串。我做了谷歌搜索,但我不能理解太多。

    我一直试到这个水平。春天我一直干到这个水平。最后,我想要一个字符串中的html标记。

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

    谢谢

    1 回复  |  直到 14 年前
        1
  •  2
  •   skaffman    15 年前

    要将发布的代码片段绑定在一起,可以执行以下操作:

    // 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);
    
        2
  •  1
  •   Razneesh    5 年前

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