2014-11-03 715 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