从数据库加载FreeMarker模板 [英] Load FreeMarker templates from database

查看:1348
本文介绍了从数据库加载FreeMarker模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的FreeMarker模板存储在类似于以下内容的数据库表中:

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}

当收到带有a的模板的请求时特定的名称,这应该导致执行查询,加载相关的模板内容。这个模板内容以及数据模型(上面例子中'user'变量的值)应该传递给FreeMarker。

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.

然而,< A HREF =http://freemarker.sourceforge.net/docs/api/index.html相对=noreferrer> FreeMarker的API 似乎假设每个模板名称对应于内的同名文件文件系统的特定目录。有没有什么方法可以轻松地从数据库而不是文件系统加载我的模板?

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?

编辑:我应该提到我会喜欢能够在应用程序运行时向数据库添加模板,所以我不能简单地在启动时将所有模板加载到新的StringTemplateLoader中(如下所示)。

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).

干杯,
Don

Cheers, Don

推荐答案

我们使用StringTemplateLoader来加载我们从db获得的tempates(如Dan Vinton建议)

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

这是一个例子:

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);

编辑
您不必加载所有模板在启动时。每当我们访问模板时,我们将从DB中获取它并通过StringLoader加载它,并通过调用template.process()生成(在我们的例子中)XML输出。

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.

这篇关于从数据库加载FreeMarker模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆