【发布时间】:2014-11-03 20:58:00
【问题描述】:
如何评估这种参数或者我需要传递 JSON?我可以更改参数的结构:"news[0].title" 或 "news.0.title" 或其他任何东西,但我不想让我的 API 的用户形成 json。
@Autowired
private TemplateEmailBodyPreparer preparer;
public void doIt() {
Map<String,String> properties = new HashMap<String,String>() {{
put("news[0].title", "Title 1");
put("news[0].body", "Body 1");
put("news[1].title", "Title 2");
put("news[1].body", "Body 2");
}};
String result = preparer.getByTemplate("mail/html/news.ftl", properties);
System.out.println("Result = " + result);
}
@Service
public class TemplateEmailBodyPreparer implements EmailBodyPreparer {
@Autowired
private Configuration freeMarkerConfiguration;
public String getByTemplate(String templatePath, Map<String,String> properties) {
try {
Template template = freeMarkerConfiguration.getTemplate(templatePath, "UTF-8");
return FreeMarkerTemplateUtils.processTemplateIntoString(template, properties);
} catch (IOException | TemplateException e) {
throw new IllegalArgumentException("Unable to build template: " + e.getMessage());
}
}
}
mail/html/news.ftl
<!DOCTYPE html>
<html>
<head></head>
<body>
<#list news as content>
${content.title} - ${content.body}
</#list>
</body>
</html>
错误:
Caused by: java.lang.IllegalArgumentException: Unable to build template: The following has evaluated to null or missing:
==> news [in template "mail/html/news.ftl" at line 5, column 11]
【问题讨论】:
-
.0-s 和.1-s 是什么?这是地图列表吗? -
@ddekany,这是数组的索引。请允许我添加一些细节。查看更新后的帖子。
-
FreeMarker 中没有
${emails.0.body}这样的东西。这是${emails[0].body}。但是对于迭代,您通常使用<#list emails as email>...${email.body}...</#list>。你卡在哪里了? -
@ddkany,我已经更新了帖子,请立即查看。
标签: java freemarker