Search code examples
javafreemarker

The following has evaluated to null or missing when executing FreeMarker


I am using FreeMarker (a free Java-based template engine, originally focusing on dynamic web page generation with MVC software architecture) to generate some HTML pages I have a freemarker template with this piece of code:

 Dear ${user.firstname} ${user.surname},</h3>

I have created this piece of code to test it :

public static void main(String[] args) throws IOException, TemplateException {


    class User {

        String firstname;

        public String getFirstname() {
            return firstname;
        }

        public void setFirstname(String firstname) {
            this.firstname = firstname;
        }





    }


    String templateName = "tdk_reminder_ext_body.ftl";

     final Map<String, Object> finalModel = new HashMap<>();

     User user = new User();

     user.setFirstname("firstname");

     finalModel.put("serverName", "local");
     finalModel.put("user", user);



    Configuration cfg = new Configuration(Configuration.getVersion());

    cfg.setDirectoryForTemplateLoading(new File("C:/Work/eclipse-tdk/templates/engine/"));
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

    final freemarker.template.Template freemarkerTemplate = cfg.getTemplate(templateName);

    System.out.println (FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerTemplate, finalModel));


}

But when I run the program I got this error:

FTL stack trace ("~" means nesting-related):
    - Failed at: ${user.firstname}  [in template "tdk_reminder_ext_body.ftl" at line 34, column 38]
----

Solution

  • Your class must be public. See the documentation.

    public class User {
    
        String firstname;
    
        public String getFirstname() {
            return firstname;
        }
    
        public void setFirstname(String firstname) {
            this.firstname = firstname;
        }
    
    }