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();
Related videos on Youtube
Comments
-
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 almost 11 yearsNote 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 customTemplateLoader
could be used (withcfg.setTemplateLoader
) that loads templates by name from the data base, because then FreeMarker will cache theTemplate
objects. (Or you can write your own caching mechanism to reuse theTemplate
-s, of course.) -
ced-b almost 9 yearsIn the latest version of Freemarker it seems like you can just pass a string without having to wrap it in a
StringReader
-
user2573153 over 8 yearsWhat 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 upConfiguration
for the latter case?