freemarker在mysql中使用,从数据库加载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}

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

Cheers,

Don

解决方案

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 = " 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值