2014-11-03 716 views
0

如何评估这种参数或我需要传递JSON?我可以改变结构的参数:"news[0].title"或“news.0.title"或其他任何东西,但我不喜欢问我的API的用户形成JSONFreemarker - 传递参数的平面结构,传递到对象数组

@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()); 
     } 
    } 
} 

邮件/ 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

什么是.0'-s和'.1'-s?这是地图列表吗? – ddekany 2014-11-04 07:16:24

+0

@ddekany,这是数组的索引。请允许我添加一些细节。查看更新的帖子。 – Ivan 2014-11-05 12:29:07

+0

尽管在FreeMarker中没有这样的东西,但它是'$ {emails.0.body}'。它是'$ {emails [0] .body}'。但是对于迭代,通常使用'<#emails email as email> ... $ {email.body} ...'。你卡在哪里? – ddekany 2014-11-05 20:03:09

回答

0

在您的示例模板FreeMarker的预计,一个真正的和真正的Map -s或JavaBeans作为该列表中的项目。它不会解释那些用特殊语言编写的关键值(它怎么可能?)。由于您知道密钥的语法,因此您必须将它们解析为List -s和Map -s,然后将结果传递给FreeMarker。

+0

好的,我明白了。有没有可能通过eval()或类似的东西来做到这一点?我不知道所有属性的结构,因此无法在Java端解析它(非常可悲)。 Freemarker支持json解析,我需要类似但没有json的东西,只有键值,但我可以选择任何格式。或者json是我的单一变体? – Ivan 2014-11-07 16:27:51