问题
How to eval this kind of parameters or I need to pass JSON? I can change structure of parameters: "news[0].title"
or "news.0.title"
or anything else but I wouldn't like to ask users of my API to form 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>
Error:
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]
回答1:
In your example template FreeMarker expects a real List
for news
, and real Map
-s or JavaBeans as the items in that list. It won't interpret those key values, written in some adhoc language (how could it?). Since you know the syntax of the keys, you will have to parse them to List
-s and Map
-s, and then pass the result to FreeMarker.
来源:https://stackoverflow.com/questions/26723088/freemarker-flat-structure-of-passing-parameters-transfer-to-array-of-objects