【问题标题】:Spring boot Thymeleaf context parameter is not passed to templateSpring boot Thymeleaf 上下文参数未传递给模板
【发布时间】:2018-05-07 10:50:37
【问题描述】:

我正在使用 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>

无论我尝试什么,我都无法获取要传递给模板的参数。

【问题讨论】:

  • 更改字符串结果 = springTemplateEngine.process("hello", ctx); to String result = springTemplateEngine.process("hello", cts);

标签: java spring-boot thymeleaf


【解决方案1】:

你试试java代码:

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>    

【讨论】:

  • 是的,我的意思是更改了 html 代码,感谢您的提醒!!
猜你喜欢
  • 2016-01-26
  • 2018-11-02
  • 2019-09-19
  • 2017-10-28
  • 1970-01-01
  • 1970-01-01
  • 2021-09-10
  • 1970-01-01
  • 2020-07-30
相关资源
最近更新 更多