java 如何在 FreeMarker 中将 String 作为输入传递?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17746399/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 14:52:16  来源:igfitidea点击:

How to pass String as input in FreeMarker?

javafreemarker

提问by Shashi

All the templates are stored in database. And i have to fetch contents of a template from database and marked up with freemarker. The end output will be rendered in a textbox.

所有模板都存储在数据库中。我必须从数据库中获取模板的内容并用 freemarker 标记。最终输出将呈现在文本框中。

But, i am not finding any methodology by which i can send string instead of file name.

但是,我没有找到任何可以发送字符串而不是文件名的方法。

Please suggest.

请建议。

回答by obourgain

You can pass your template to the Templateconstructor with a StringReader:

您可以使用StringReader模板传递给模板构造函数:

  // Get your template as a String from the DB
  String template = getTemplateFromDatabase();
  Map<String, Object> model = getModel();

  Configuration cfg = new Configuration();
  cfg.setObjectWrapper(new DefaultObjectWrapper());

  Template t = new Template("templateName", new StringReader(template), cfg);

  Writer out = new StringWriter();
  t.process(model, out);

  String transformedTemplate = out.toString();