Using Java Properties in Freemarker

Hi

I have a typical messages.properties file in my application. I am trying to create a letter using Freemarker.

The Freemarker template should generate before String , after which I will email the String user to the user. However, we need this multilingual. So Properties came to mind.

My properties file is as follows:

 mail.layout.contactus=Contacteer ons mail.layout.greeting=Hoi 

In Java, I inject a Properties file into my HashMap as follows:

 rootMap.put("lang", (mail.getLanguage().equals(Language.FRENCH) ? langFR : langNL)); 

And try reading it in FreeMarker as follows:

 <p>${lang.mail.layout.greeting} ${user.firstname},</p> 

But get the following exception:

 freemarker.core.InvalidReferenceException: Expression lang.mail is undefined on line 10, column 116 in layout/email.ftl. 

Strange, he only says lang.mail , not lang.mail.layout.greeting

Edit: I tried to define my keys as follows:

 mail_layout_contactus=Contacteer ons mail_layout_greeting=Hoi 

which is working

+6
source share
1 answer

I believe the problem is that with the lang.mail.layout.greeting key, Freemarker considers each part between . like hash , that is, a container that can have sub-options. So he tries to get the object that lang refers to from the data model, and then tries to get the variable that mail from lang refers to. In your case, however, there is no such object, therefore, an error.

The documentation has about variable names :

In this expression, the variable name can only contain letters (including non-Latin letters), numbers (including non-Latin numbers), underscore (_), dollar ($), with the sign (@) and hash (#). In addition, the name should not begin with numbers.

You can use alternative syntax to get data from the hash (while the expression evaluates to a string)

 <p>${lang["mail.layout.greeting"]} ${user.firstname},</p> 
+4
source

Source: https://habr.com/ru/post/888238/


All Articles