How to pass String as input in FreeMarker?

15,138

You can pass your template to the Template constructor with a 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();
Share:
15,138

Related videos on Youtube

Shashi
Author by

Shashi

Learning new curve everyday..

Updated on September 26, 2022

Comments

  • Shashi
    Shashi over 1 year

    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.

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

    Please suggest.

  • ddekany
    ddekany almost 11 years
    Note that if you want good performance, the Configuration should not be re-created (or re-configured) before each template processing; it should be a singleton. Also, re-parsing the templates again and again (for the string) can be too slow in some applications; in that case, a custom TemplateLoader could be used (with cfg.setTemplateLoader) that loads templates by name from the data base, because then FreeMarker will cache the Template objects. (Or you can write your own caching mechanism to reuse the Template-s, of course.)
  • ced-b
    ced-b almost 9 years
    In the latest version of Freemarker it seems like you can just pass a string without having to wrap it in a StringReader
  • user2573153
    user2573153 over 8 years
    What if you are trying to allow users to test templates? IE there are two ways to use the system. The normal use case is to load from the database (and I have a custom TemplateLoader for it) but I also want the users to be able to test the templates as they edit them. I have my singleton instance for the first case, is it reasonable to new up Configuration for the latter case?