Use Java Properties in Freemarker

2019-06-18 14:43发布

HI,

I have a typical messages.properties file in my application. I'm trying to generate an email using Freemarker.

The Freemarker template should generate to a String, after which I'll send the String to the user via email. However, we need it multilingual. So Properties came to mind.

My properties file looks like this:

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

In Java, I enter the Properties file in my HashMap like this:

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

And try to read it in FreeMarker like this:

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

But get following exception:

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

Strangely, it only says lang.mail as opposed to lang.mail.layout.greeting

Edit: I tried defining my keys like this:

mail_layout_contactus=Contacteer ons
mail_layout_greeting=Hoi

which does work

1条回答
来,给爷笑一个
2楼-- · 2019-06-18 15:37

I believe the problem is that with a key of lang.mail.layout.greeting, Freemarker treats each part between the .s as a hash i.e. a container variable that can have subvariables. So it attempts to get the object referenced by lang from the data-model and then attempts to get the variable referenced by mail from lang. In your case, however, there is no such object, hence the error.

The documentation has this to say about variable names:

In this expression the variable name can contain only letters (including non-Latin letters), digits (including non-Latin digits), underline (_), dollar ($), at sign (@) and hash (#). Furthermore, the name must not start with digit.

You might make use of the alternative syntax to get data from a hash (as long as the expression evaluates to a string)

<p>${lang["mail.layout.greeting"]} ${user.firstname},</p>
查看更多
登录 后发表回答