How can I include thymeleaf with multiple language support?

2.1k Views Asked by At

I want to show a page with different languages. I know to use message properties for different languages but this isn't solve my problem. Because my html page has a lot of dynamic variables. And I want to include page with language option. How can I solve this problem easily in thymeleaf?

1

There are 1 best solutions below

1
T.UK On

To support multiple languages I would personally use Spring Framework's Internationalization: http://www.baeldung.com/spring-boot-internationalization - works easily with thymeleaf templates

So here is a solution below:

@Controller

public class MvcWebConfig implements WebMvcConfigurer {

/*THis locates all message files for html pages */
@Bean("messageSource")
public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource messageSource =
            new ReloadableResourceBundleMessageSource();
    messageSource.setBasename("classpath:messages");
    messageSource.setDefaultEncoding("UTF-8");
    messageSource.setUseCodeAsDefaultMessage(true);
    return messageSource;
}


/*Local Resolver is to set language preference */
@Bean
public LocaleResolver localeResolver() {
    SessionLocaleResolver LR = new SessionLocaleResolver();
    LR.setDefaultLocale(Locale.UK);
    return LR;
}


/*overides language default with preference */

@Override
public void addInterceptors(InterceptorRegistry registry) {
    LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor();
    localeChangeInterceptor.setParamName("lang");
    registry.addInterceptor(localeChangeInterceptor);
}

}

Then to implement this in thymeleaf

Language : <a href="?lang=uk">English</a> | <a href="?lang=gd">Gaelic</a>