0

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>

Error:

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]
ABC
  • 4,263
  • 10
  • 45
  • 72
Ivan
  • 465
  • 5
  • 19
  • What are those `.0`-s and `.1`-s? Is this a list of maps? – ddekany Nov 04 '14 at 07:16
  • @ddekany, this is indexes of array. Please, allow me to add some details. See updated post. – Ivan Nov 05 '14 at 12:29
  • There's no such thing in FreeMarker as `${emails.0.body}` though. It's `${emails[0].body}`. But for iteration generally you use `<#list emails as email>...${email.body}...#list>`. Where do you stuck? – ddekany Nov 05 '14 at 20:03
  • @ddkany, I have updated post, please take a look now. – Ivan Nov 06 '14 at 07:10

1 Answers1

0

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.

ddekany
  • 29,656
  • 4
  • 57
  • 64
  • ok, I see. And there is no possibilities to do that via eval() or something like that? I don't know a structure of all properties so it is unable to parse it on Java side (very sadly). Freemarker support json parsing, I need something like that but without json, only key-values, but I can choose any format. Or json is my single variant? – Ivan Nov 07 '14 at 16:27