vincent zhang
vincent zhang

Reputation: 454

Thymeleaf set message resource without WEB

In this scenario, there is no web config, no Spring MVC, no Spring Boot etc. Just pure Application, I would like to use Thymeleaf transfer static html resource, and get the content in String.

However, in this case, how to set the internation message for thymeleaf? So I could in static html file use like

<h1 th:text="#{messageA}">AAAAA</h1>

Upvotes: 1

Views: 930

Answers (1)

Metroids
Metroids

Reputation: 20487

You just need to define a message source. For example, in my spring configuration, I have a main method:

@Configuration
@ComponentScan(basePackages = {"spring.cli.config"})
public class Main {
    public static void main(String... args) throws Exception {
        ConfigurableApplicationContext spring = new SpringApplicationBuilder(Main.class)
                .web(NONE)
                .profiles("default")
                .run(args);

        TemplateEngine engine = (TemplateEngine) spring.getBean("engine");
        Context context = new Context();
        System.out.println(engine.process("template", context));
    }
}

and a configuration file (scanned in @ComponentScan(basePackages = {"spring.cli.config"})):

@Configuration
public class Thymeleaf {
    @Bean
    public MessageSource messageSource() throws Exception {
        ReloadableResourceBundleMessageSource res = new ReloadableResourceBundleMessageSource();
        res.setBasename("file:src/main/resources/messages");
        return res;
    }
}

I have a file in my project src/main/resources/messages.properties.

# messages.properties
messageA=Hello I am message A

And in the html:

<h1 th:text="#{messageA}">AAAAA</h1>

resolves to:

<div>Hello I am message A</div>

Upvotes: 2

Related Questions