Tom Marthenal
Tom Marthenal

Reputation: 3146

Best practice for translations

I'm writing a website using JSP. I want to have the website available in multiple languages, so I've created a HashMap for each language I plan to support, and am finding the text via map.get("identifier") (with some other code, of course.)

The problem I'm having is one I've solved before by using a formatfunction (similar to printf in many languages), but this was in another language.

The problem specifically is that text like User performed action may be come Action was performed by user in another language (i.e. the terms may become out of order).

In the past, I've done something like #translate("Welcome to the site, %s!", {"Username"}), and then used the language's format function to replace %s with the username. I could simply use String#replace but then I can't do something like #translate("Welcome to the site, %s! You last visited on %s!", {"username", "last visit"}) like I'd like to.

Sorry if this is a bad explanation—just look up printf in something like PHP.

What would be the best way to replicate something like this in Java? Thanks for the help.

Upvotes: 4

Views: 1326

Answers (3)

BalusC
BalusC

Reputation: 1108712

Don't reinvent. Use JSTL fmt taglib. It supports parameterized messages as well.

<fmt:message key="identifier">
  <fmt:param value="${username}" />
</fmt:message>

See also:

Upvotes: 9

x.509
x.509

Reputation: 2235

use property files to have different languages

en_US.properties
fr_CA.properties

and in those properties file, have your text like that

user.performed.action=User performed an action

and then as BalusC said, use JSTL.

Upvotes: 0

Beccari
Beccari

Reputation: 761

I've stuck myself in that question and I find out that the best way is to use resource bundle like everyone (or almost every one) does. You can use the fmt taglib or the spring message.

I tried to use the gettext solution, but it includes some previous steps (xgettext, msgmerge, msgfmt) which makes this too complex and it is not so good for webapp (in my opinion).

I'm going to use the spring message, you can see an example on:

http://viralpatel.net/blogs/2010/07/spring-3-mvc-internationalization-i18n-localization-tutorial-example.html

Upvotes: 1

Related Questions