Spring引导Thymeleaf上下文参数未传递给模板

时间:2017-11-23 12:54:11

标签: java spring-boot thymeleaf

我使用百日咳作为模板引擎,但我无法让它正常工作。

我使用websockets将html推送到Web浏览器,因此我尝试将带有上下文的模板处理成字符串。然后将此字符串发送到浏览器以显示。

我的控制器类:

@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);
}

我的百里香配置:

@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;
}
}

我的hello.html模板:

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

当我从send方法打印字符串结果时,我得到了这个输出:

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

无论我尝试什么,我都无法将参数传递给模板。

1 个答案:

答案 0 :(得分:1)

你试试java代码:

"""

Html:hello.html

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