When a user select a language in my app, the language is stored in a cookie, to remember the language the next session.
But where/when is it appropriate to read the cookie and set the language when starting a new session - such that is set before any page is loaded (e.g. login page, about page, etc)?
The simplest would be to read the cookie in the BeforeEnterObserver.beforeEnter in every view.
You can create a base class that implements that code for your views.
Then you don’t have to care if it’s already set or not.
Tatu2
(Tatu Lund)
August 12, 2024, 10:18am
3
In my example app I do it in afterNavigation of the login view.
}
@Override
public void localeChange(LocaleChangeEvent event) {
loginForm.setI18n(getI18n());
loginInfoText.setText(getTranslation(LOGIN_INFO_TEXT));
loginInfoHeader.setText(getTranslation(LOGIN_INFO));
}
@Override
public void afterNavigation(AfterNavigationEvent event) {
Cookie localeCookie = CookieUtil.getCookieByName("language",
VaadinRequest.getCurrent());
if (localeCookie != null && localeCookie.getValue() != null) {
logger.info("Using stored locale {} from cookie.",
localeCookie.getValue());
locale = CustomI18NProvider.locales.stream()
.filter(loc -> loc.getLanguage()
.equals(localeCookie.getValue()))
.findFirst();
lang.setValue(locale.get());
The same app provides you example how to persist the selected language to cookie as well using request handler.
I’m usually doing this, if you’re using Spring Boot:
@Component
public class ApplicationFormBaseUIInitializer implements VaadinServiceInitListener {
@Override
public void serviceInit(ServiceInitEvent event) {
event.addIndexHtmlRequestListener(indexHtmlResponse -> {
String lang = readCookie(indexHtmlResponse.getVaadinRequest().getCookies(), "locale").orElse("de-DE");
Locale locale = Locale.forLanguageTag(lang);
indexHtmlResponse.getDocument().getElementsByTag("html")
.attr("lang", locale.getLanguage());
VaadinSession.getCurrent().setLocale(locale);
});
}
public Optional<String> readCookie(Cookie[] cookies, String key) {
if (cookies == null) {
return Optional.empty();
}
return Arrays.stream(cookies)
.filter(c -> key.equals(c.getName()))
.map(Cookie::getValue)
.findFirst();
}
}
It will be set the correct html tag from the cookie and set the locale of the Vaadin session. (see the open ticket here: Lang attribute on the html tag is not in sync with the UI locale · Issue #18585 · vaadin/flow · GitHub )
I do indeed. This looks pretty neat. I’ll try it out