Load FreeMarker templates from database

Dónal picture Dónal · Dec 10, 2008 · Viewed 19k times · Source

I would like to store my FreeMarker templates in a database table that looks something like:

template_name | template_content
---------------------------------
hello         |Hello ${user}
goodbye       |So long ${user}

When a request is received for a template with a particular name, this should cause a query to be executed, which loads the relevant template content. This template content, together with the data model (the value of the 'user' variable in the examples above), should then be passed to FreeMarker.

However, the FreeMarker API seems to assume that each template name corresponds to a file of the same name within a particular directory of the filesystem. Is there any way I can easily have my templates loaded from the DB instead of the filesystem?

EDIT: I should have mentioned that I would like to be able to add templates to the database while the application is running, so I can't simply load all templates at startup into a new StringTemplateLoader (as suggested below).

Answer

Ulf Lindback picture Ulf Lindback · Dec 10, 2008

We use a StringTemplateLoader to load our tempates which we got from the db (as Dan Vinton suggested)

Here is an example:

StringTemplateLoader stringLoader = new StringTemplateLoader();
String firstTemplate = "firstTemplate";
stringLoader.putTemplate(firstTemplate, freemarkerTemplate);
// It's possible to add more than one template (they might include each other)
// String secondTemplate = "<#include \"greetTemplate\"><@greet/> World!";
// stringLoader.putTemplate("greetTemplate", secondTemplate);
Configuration cfg = new Configuration();
cfg.setTemplateLoader(stringLoader);
Template template = cfg.getTemplate(firstTemplate);

Edit You don't have to load all templates at startup. Whenever we will access the template, we'll fetch it from the DB and load it through the StringLoader and by calling template.process() we generate (in our case) the XML output.