Spring boot Thymeleaf context parameter is not passed to template

Viewed 3300

I'm using thymeleaf as a template engine but I cant get it to work properly.

I'm using websockets to push html to the web browser so I try to process the template with the context into a string. This string is then send to the browser to show.

My Controller class:

@Autowired
private SimpMessagingTemplate simpMessagingTemplate;

@Autowired
private SpringTemplateEngine springTemplateEngine;

private void send() {
    Map<String, Object> params = new HashMap<>();
    params.put("name", "Willem");

    final IContext cts = new Context(Locale.ITALY, params);
    String result = springTemplateEngine.process("hello", ctx);

    simpMessagingTemplate.convertAndSend(destination, result);
}

My thymeleaf configuration:

@Configuration
public class ThymeleafConfig extends WebMvcConfigurerAdapter {

@Bean
public ClassLoaderTemplateResolver templateResolver() {
    ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();

    templateResolver.setPrefix("thymeleaf/");
    templateResolver.setCacheable(false);
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode("HTML5");
    templateResolver.setCharacterEncoding("UTF-8");

    return templateResolver;
}

@Bean
public SpringTemplateEngine templateEngine() {
    SpringTemplateEngine templateEngine = new SpringTemplateEngine();

    templateEngine.setTemplateResolver(templateResolver());

    return templateEngine;
}

@Bean
public ViewResolver viewResolver() {
    ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();

    viewResolver.setTemplateEngine( templateEngine());
    viewResolver.setCharacterEncoding("UTF-8");

    return viewResolver;
}
}

And my hello.html template:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/xhtml">
<body> 
    <h2>Hello ${name} - THYMELEAF</h2>
</body>
</html>

When I print the string result from the send method, I get this output:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body> 
    <h2>Hello ${name} - THYMELEAF</h2>
</body>
</html>

Whatever I try, I can't get the parameters to be passed to the template.

1 Answers

You try java code:

private void send() {
   Context context = new Context();
   context.setVariable("name", "hello");
   String result = springTemplateEngine.process("hello", context);
   simpMessagingTemplate.convertAndSend(destination, result);
}

Html: hello.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body> 
  <h2>Hello <b th:text="${name}"></b> - THYMELEAF</h2>
</body>
</html>    
Related