1

私はfreemarkerを初めて使用します。freemarkerで使用する予定のSpringアプリケーションがあります。テンプレートはデータベースに保存され、ログインに基づいてデータベースからテンプレートを取得したいと思います。春にフリーマーカーを設定し、テンプレートを作成した後にhtmlタグを文字列として取得する方法を教えてもらえますか?グーグルをしましたが、よくわかりませんでした。

このレベルまでやってみました。春に私はこのレベルまでやりました。最後に、文字列にhtmlタグが必要です。

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

ありがとう。

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タグをStringとして提供します。

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 に答える