Freemarker - 传递参数的平面结构,传递给对象数组

时间:2014-11-03 20:58:00

标签: 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>() {{
        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]

1 个答案:

答案 0 :(得分:0)

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