Freemarker-传递参数的平面结构,传输到对象数组 [英] Freemarker - flat structure of passing parameters, transfer to array of objects

查看:214
本文介绍了Freemarker-传递参数的平面结构,传输到对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何评估此类参数,或者我需要传递JSON?我可以更改参数的结构:"news[0].title"或"news.0.title"或其他任何内容,但我不想让我的API用户形成json.

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>

错误:

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]

推荐答案

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

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.

这篇关于Freemarker-传递参数的平面结构,传输到对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆