Java Freemarker-传递参数的平面结构,传递到对象数组
如何评估此类参数,或者我需要传递JSON?我可以更改参数的结构:Java Freemarker-传递参数的平面结构,传递到对象数组,java,freemarker,Java,Freemarker,如何评估此类参数,或者我需要传递JSON?我可以更改参数的结构:“news[0].title“或“news.0.title”或其他任何内容,但我不想要求API的用户形成json @Autowired private TemplateEmailBodyPreparer preparer; public void doIt() { Map<String,String> properties = new HashMap<String,String>() {{
“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());
}
}
}
在您的示例模板中,FreeMarker希望
新闻有一个真正的列表,而真正的地图-s或JavaBeans是该列表中的项目。它不会解释那些用某种特殊语言编写的关键值(怎么可能?)。由于您知道键的语法,因此必须将它们解析为列表
-s和映射
-s,然后将结果传递给FreeMarker。这些.0
-s和.1
-s是什么?这是地图列表吗?@ddekany,这是数组的索引。请允许我补充一些细节。请参阅更新的帖子。不过,FreeMarker中没有${emails.0.body}
这样的东西。这是${emails[0].body}
。但对于迭代,通常使用…${email.body}…
。你卡在哪里了?@ddkany,我已经更新了帖子,现在请看一下。好的,我明白了。没有可能通过eval()或类似的方式实现这一点?我不知道所有属性的结构,所以它无法在Java端解析它(非常遗憾)。Freemarker支持json解析,我需要类似的东西,但没有json,只有键值,但我可以选择任何格式。或者json是我的单一变体?
<!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]