在Freemarker中使用Java属性 [英] Use Java Properties in Freemarker

查看:179
本文介绍了在Freemarker中使用Java属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI

我的应用程序中有一个典型的messages.properties文件. 我正在尝试使用Freemarker生成电子邮件.

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

Freemarker模板应生成为String,然后我将通过电子邮件将String发送给用户.但是,我们需要多语言. 所以Properties浮现在脑海.

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.

我的属性文件如下:

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

在Java中,我在HashMap中输入Properties文件,如下所示:

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

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

并尝试像这样在FreeMarker中阅读它:

And try to read it in FreeMarker like this:

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

但是出现以下异常:

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

奇怪的是,它只说了lang.mail而不是lang.mail.layout.greeting

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

我尝试过这样定义键:

I tried defining my keys like this:

mail_layout_contactus=Contacteer ons
mail_layout_greeting=Hoi

有效

推荐答案

我相信问题在于,使用lang.mail.layout.greeting键,Freemarker将.之间的每个部分都视为

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.

文档中关于变量名的说法:

在此表达式中,变量名称只能包含字母(包括非拉丁字母),数字(包括非拉丁数字),下划线(_),美元($),符号(@)和哈希(#) .此外,名称不能以数字开头.

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>

这篇关于在Freemarker中使用Java属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆