在模板中命名范围

时间:2013-03-19 21:51:35

标签: freemarker

是否可以在ftl中命名一些块并在java端获取它们?例如,使用不正确的语法可能

#emailSubject[
This is email subject]
#emailMessage
[Email multi-
line message!!
Hi all]

和java方面看起来像

template.process("template.ftl", resultModelOrSomethingElse);
String emailSubject = resultModelOrSomethingElse.getEmailSubject();
String emailMessag = resultModelOrSomethingElse.getEmailMessage();

1 个答案:

答案 0 :(得分:1)

开箱即用,你可以这样做:

<#assign emailSubject>This is the email subject</#assign>

<#assign emailMessage>
  This is the email message...
</#assign>

然后:

// Same as template.process, but you will have the Environment:
Environment env = template.createProcessingEnvironment(dataModel, out);
env.process();

// Extract top-level variables:
TemplateModel emailSubject = env.getVariable("emailSubject");
TemplateModel emailMessage = env.getVariable("emailMessage");

(如果你会做很多事情,你可能想在模板中简化这一点。像<@emailSubject>This is the email subject</@>更简洁,更加万无一失,因为如果有人犯了错误,它会立即失败。 “emailSubject”变量名称。)