mercoledì 15 dicembre 2010

FreeMarker and custom parameters on templates

Sometime it's usefull to get some parameters from templates, for example, I use a parameter in an email template to store the subject of this mail.

FreeMarker has a specific directive to do this: ref_directive_ftl but the section about custom parameters don't show how to use this. Here is an example:
Template:
 <#ftl attributes={ "subject": "Registrazione"}>  
 <html>  
      <body>  
           Gentile utente  
.....

This is the java code to read the parameter:
 Template template = cfg.getTemplate(stemplate);  
 String subject = template.getCustomAttribute("subject");  

I spent the last 3 hours to find the correct form of ftl's attributes. I used attributes={ subject: Registrazione} and attributes="{subject: Registrazione}" and I get ris respectively this error:

 freemarker.core.ParseException: Could not evaluate expression: {subject : Registrazione} on line 1, column 18 in it/mail/Registration.html  
 Underlying cause: Variables are not available (certainly you are in a parse-time executed directive). The name of the variable you tried to read: subject in it/mail/Registration.html  
      at freemarker.core.FMParser.HeaderElement(FMParser.java:2831)  
      at freemarker.core.FMParser.Root(FMParser.java:2954)  
      at freemarker.template.Template.<init>(Template.java:149)  

and

 freemarker.core.ParseException: Expecting a hash of attribute names to values here. on line 1, column 18 in it/mail/Registration.html in it/mail/Registration.html  
      at freemarker.core.FMParser.HeaderElement(FMParser.java:2888)  
      at freemarker.core.FMParser.Root(FMParser.java:2954)  
      at freemarker.template.Template.<init>(Template.java:149)  
      at freemarker.cache.TemplateCache.loadTemplate(TemplateCache.java:448)  
      at freemarker.cache.TemplateCache.getTemplate(TemplateCache.java:361)  
      at freemarker.cache.TemplateCache.getTemplate(TemplateCache.java:235)  

Nice FreeMarker!