gpt4 book ai didi

java - Spring boot Thymeleaf 上下文参数未传递给模板

转载 作者:行者123 更新时间:2023-11-30 10:22:08 24 4
gpt4 key购买 nike

我正在使用 thymeleaf 作为模板引擎,但我无法让它正常工作。

我正在使用 websockets 将 html 推送到网络浏览器,因此我尝试将模板和上下文处理成一个字符串。然后将该字符串发送到浏览器以显示。

我的 Controller 类:

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

我的 thymeleaf 配置:

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

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

最佳答案

你试试java代码:

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

HTML: 你好.html

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

关于java - Spring boot Thymeleaf 上下文参数未传递给模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47456045/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com