Liferay provides a very useful text localization method, which can be used with LanguageUtil
Java class (and its counterpart class UnicodeLanguageUtil
) or with <liferay-ui:message/>
taglib.
But how can we use the same method with Javascript? Let's see!
Let's suppose to have created a Liferay plugin, with the usual translation property file Language.properties
and the following items:
sample-text=Sample text sample-text-with-param-x=Sample text with param: {0}
As we said above, it's possibile to display translated messages with taglib:
<liferay-ui:message key="sample-text" /> <liferay-ui:message key="sample-text-with-param-x" arguments='<%=new String[] { "Foo" }%>' />
Or with Java class:
LanguageUtil.get(pageContext, "sample-text"); LanguageUtil.format(pageContext, "sample-text-with-param-x", new String[] {"Foo"});
Both methods above will produce the same output:
Sample text Sample text with param: Foo
But if we need a translation in a Javascript function, how can we do? Fortunately there's the not so well documented Liferay provided library and especially the Javascript object Liferay.Language
.
With this Javascript object, we can use the localization method in this way:
alert(Liferay.Language.get('sample-text')); alert(Liferay.Language.get('sample-text-with-param-x', ['Foo']));
But there's only a limitation in Javascript localization method: Liferay.Language
object searchs the translation in the portal scope and not in the portlet scope.
So every message we need to use with Javascript, must be define with a language hook.