Use Java Properties in Freemarker

99封情书 提交于 2019-12-08 17:19:14

问题


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:


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>


来源:https://stackoverflow.com/questions/6020126/use-java-properties-in-freemarker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!