3

I have the following method that renders a list of users on the template, but I got a 500 Internal Error when firing up Spark in IntelliJ.

private void renderTemplate() throws IOException, TemplateException {
        List<String> users = new ArrayList<>();
        users.add("John Doe");
        users.add("Tony Doe");

        get("/admin", (request, response) -> {
           return new ModelAndView(users, "spark/template/freemarker/admin_template.ftl");
        }, new FreeMarkerEngine());
    }

The content of my admin_template.ftl is:

<html>
<head>
    <title>Administration</title>
</head>
<body>


<h1>My Admin</h1>

<#list users as user>
    <h2>$user</h2>
</#list>
</body>
</html>

Does anyone know how to render the list on freemarker template? thanks for replies!

zero323
  • 322,348
  • 103
  • 959
  • 935
TonyW
  • 18,375
  • 42
  • 110
  • 183
  • tonygw : the answer by @nwk works fine and also to catch the error. you can include one error.ftl and call that to display any error message. Basically try to use try/catch block. so when you get an error either log it. and display that error page. and that way you can see the logs to find the error – govindpatel Feb 15 '16 at 14:42

1 Answers1

2

To render the list change

<#list users as user>
    <h2>$user</h2>
</#list>

to

<#list users as user>
    <h2>${user}</h2>
</#list>

in admin_template.ftl and alter renderTemplate to read as follows:

private void renderTemplate() throws IOException, TemplateException {
        List<String> users = new ArrayList<>();
        users.add("John Doe");
        users.add("Tony Doe");

        Map<String, Object> attributes = new HashMap<>();
        attributes.put("users", users);    

        get("/admin", (request, response) -> {
           return new ModelAndView(attributes, "spark/template/freemarker/admin_template.ftl");
        }, new FreeMarkerEngine());
    }

If this does not resolve the problem there may be a separate issue with FreeMarkerEngine that is causing the error messages "500 Internal Error", namely, that your FreeMarkerEngine object fails to find the template file admin_template.ftl at runtime. See the answer to FileNotFoundException when loading freemarker template in java for details on how to deal with that.

Community
  • 1
  • 1
nwk
  • 4,004
  • 1
  • 21
  • 22