Monday, 26 October 2015

internationalization in java class liferay

Hi in this post I want to share how we internationalize in class.
There are number of ways to translate/I18N in liferay.

in jsp we can simply achieve by using tag

<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
<liferay-ui:message key="overview" />

<%
     String replyToo = LanguageUtil.get(pageContext,"my-reply")+" <b>"+anyVar+"</b>";
%>

Instead of pageContext we can also use themeDisplay.getLocale(), locale object but it is some time doesn't reflect the output as we change language. Means I faced some problem by using locale object.
It is better to use pageContext object.
pageContext is implicit object in jsp but how to achieve this in java class.

So in .java file


String value = StringPool.BLANK;
ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);
PortletConfig portletConfig = (PortletConfig)request.getAttribute(JavaConstants.JAVAX_PORTLET_CONFIG);
Locale locale = themeDisplay.getLocale();
value = LanguageUtil.get(portletConfig, locale, "key");

Here "key",  "overview", "my-reply" will be in you language.properties(resource budle) file.

where anyVar is a variable in my jsp, you don't have to use or you can use with your variable(s).

Now if there is any requirement that we want to pass object that must attached with key/value pair of language.properties file


String jawed = "my name is jawed";
String aftab = "my father name is aftab";
themeDisplay.translate("updated-by-asif", new Object[] {jawed, aftab})

key in language.properties file

updated-by-asif={0} and {1}

here jawed and aftab is replaced by there values and "and" is attached with them.
So the output is
my name is jawed and my father name is aftab

NOTE: One more thing I want to mention here is that some time we don't have request object, means we are not render, serveResource or action method. Then first we have to create request object. One of the way is that we can get request object by using ServiceContext object.
I am working on lesson notification handler where I don't have request and response object(of any type).
But I have ServiceContext object.
LiferayPortletRequest request = serviceContext.getLiferayPortletRequest();
Now we can use this as our request object.
Thanks

No comments:

Post a Comment