Expand my Community achievements bar.

Don’t miss the AEM Skill Exchange in SF on Nov 14—hear from industry leaders, learn best practices, and enhance your AEM strategy with practical tips.

I18n access from @Model(adaptables = Resource.class)

Avatar

Level 2

I need to access the translations library from my Model - Resource.class

I manage to do it within a Model - SlingHttpServletRequest.class

To instantiate i18n I need either the slingHttpServletRequest, or the resourceBundle but, from within my humble resource class,

I am not being able to get any of them.

I tried with @Model(adaptables= {Resource.class, SlingHttpServletRequest.class}), but when I try to inject the request the my page does not render.

Does any of you manages to access i18n from a @model Resource.class?

Any help would be greatly appreciated!

7 Replies

Avatar

Level 6

following snippet might help

@Model(adaptables = {SlingHttpServletRequest.class, Resource.class})

public class SimpleModel { 

   @Self(injectionStrategy = InjectionStrategy.OPTIONAL)

  private SlingHttpServletRequest request;

  private I18n i18n;

  if (request != null) {

        i18n=new I18n(request);

  String val =i18n.getVar(“key”);

  }

}

Ref: aem-core-wcm-components/ButtonImpl.java at master · Adobe-Marketing-Cloud/aem-core-wcm-components · ...

Avatar

Level 2

I actually tried that, but the request never gets filled.

I will try to see if I can make it work, and come back if so.

Thanks for the help!

Avatar

Level 1

Hey

you can give a try in another way like

final Locale pageLocale = getCurrentPage().getLanguage(false);

final ResourceBundle resourceBundle = getRequest().getResourceBundle(pageLocale);

final I18n i18n = new I18n(resourceBundle);

Avatar

Level 6

HI guys either way it should work

Avatar

Level 2

Well, in the, and since adapting to both didn't work for me,

we made the model

@Model(adaptables = SlingHttpServletRequest.class)

and injected everything else

@Inject
private ResourceResolver resolver;

@Inject
private Resource resource;


@Inject
@Optional
private I18n i18n;

Thanks for the suport!

Avatar

Level 6

Did the above snippet work ? is request getting injected ?

Avatar

Level 2

Yes it got Injected.

But I actually, today, got a better way of getting it, without the need to adapt from slinghttpservletrequest

@Model(adaptables = Resource.class)

public class MyClassMode {

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

private ResourceBundleProvider i18nProvider;

}