Getting localization messages in Sling Models

Based on the info from Sling Internationalization Support page, here’s how we can get the reference to resource bundles in Sling Models.

If Sling Model is adapted from Resource object:

import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.Self;

import javax.inject.Inject;
import javax.annotation.PostConstruct;

@Model(adaptables = Resource.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class SomeModel {

@Self
private Resource resource;

@Inject
private ResourceResolver resourceResolver;

@Inject
@Filter("(component.name=org.apache.sling.i18n.impl.JcrResourceBundleProvider)")
private ResourceBundleProvider i18nProvider;

// ...

@PostConstruct
protected void init() {
// ...

PageManager pm = resourceResolver.adaptTo(PageManager.class);
Page currentPage = pm.getContainingPage(resource);

Locale currentLocale = currentPage.getLanguage(true);
if(i18nProvider != null) {
ResourceBundle bundle = i18nProvider.getResourceBundle(currentLocale);
String localizationMessage = bundle.getString("some.key");
// do something with localizationMessage
}

// ...
}

}

The LDAP-like filtering in selected lines is important. We have to specify the exact implementation of ResourceBundleProvider interface.

If Sling Model is adapted from SlingHttpServletRequest object:

import com.day.cq.i18n.I18n;
import com.day.cq.wcm.api.Page;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.Self;
import org.apache.sling.models.annotations.injectorspecific.ScriptVariable;

import javax.inject.Inject;
import javax.annotation.PostConstruct;

@Model(adaptables = SlingHttpServletRequest.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class SomeModel {

@Self
private SlingHttpServletRequest request;

@ScriptVariable
private Page currentPage;

// ...

@PostConstruct
protected void init() {
Locale pageLocale = currentPage.getLanguage(true);
ResourceBundle bundle = request.getResourceBundle(pageLocale);
I18n i18n = new I18n(bundle);
String localizedMessage = i18n.get("some.key")
// do something with localized message
}

}