Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring, Thymeleaf and localized strings

I am new to using Spring and Thymeleaf and I can't figure out where to put my localization .properties files. I have this Bean:

@Bean
public MessageSource messageSource() {

    ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
    messageSource.setBasenames("classpath:messages/messages", "classpath:messages/validation");
    // if true, the key of the message will be displayed if the key is not
    // found, instead of throwing a NoSuchMessageException
    messageSource.setUseCodeAsDefaultMessage(false);
    messageSource.setDefaultEncoding("UTF-8");
    // # -1 : never reload, 0 always reload
    messageSource.setCacheSeconds(0);

    return messageSource;
}

Inside login.html:

    <p th:text="#{messages.hello}">Welcome to our site!</p>

Inside messages_en.properties :

    messages.hello=Apparently messages work

My project structure:

structure

I have tried creating a folder inside WEB-INF called messages but apparently I am not getting something right. Any ideas?

Edit: Updated question with code relevant to mesages.

like image 299
Chris Margonis Avatar asked Dec 11 '13 15:12

Chris Margonis


2 Answers

I know this one is old. But I have looked for a solution and got to this post.
I have found a solution by myself and others with the same problem might get here.

So this is how I solved it:

Inject MessageSource into SpringTemplateEngineBean.

@Bean
public SpringTemplateEngine templateEngine(MessageSource messageSource, ServletContextTemplateResolver templateResolver) { 
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setTemplateResolver(templateResolver);
    engine.setMessageSource(messageSource);
    return engine;
}

Now Thymeleaf knows about your MessageSource and evaluates your expressions.

like image 200
blackanthrax Avatar answered Sep 22 '22 10:09

blackanthrax


Basename in this XML means prefix of .properties files that contain different translations.

Let's say that you need two languages: English (en) and Polish (pl). All you need to do is to set your Basename to messages like this:

messageSource.setBasename("classpath:messages");

and then put two files messages_en and messages_pl in your classpath (WEB-INF should suffice, although consider using src/main/resources directory).

This is a basic example that should be easily adapted to your case.

like image 43
Michał Rybak Avatar answered Sep 21 '22 10:09

Michał Rybak