【问题标题】:Freemarker - flat structure of passing parameters, transfer to array of objectsFreemarker - 传递参数的平面结构,转移到对象数组
【发布时间】:2014-11-03 20:58:00
【问题描述】:

如何评估这种参数或者我需要传递 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());
        }
    }
}

ma​​il/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-s 和 .1-s 是什么?这是地图列表吗?
  • @ddekany,这是数组的索引。请允许我添加一些细节。查看更新后的帖子。
  • FreeMarker 中没有 ${emails.0.body} 这样的东西。这是${emails[0].body}。但是对于迭代,您通常使用&lt;#list emails as email&gt;...${email.body}...&lt;/#list&gt;。你卡在哪里了?
  • @ddkany,我已经更新了帖子,请立即查看。

标签: java freemarker


【解决方案1】:

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

【讨论】:

  • 好的,我明白了。并且没有可能通过 eval() 或类似的方法来做到这一点?我不知道所有属性的结构,因此无法在 Java 端解析它(非常遗憾)。 Freemarker 支持 json 解析,我需要类似的东西,但没有 json,只有键值,但我可以选择任何格式。还是 json 是我的单一变体?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 2020-04-20
  • 1970-01-01
  • 2015-11-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多