要正确渲染Thymeleaf模板中的变量,需要注意以下几点:
@GetMapping("/example")
public String example(Model model) {
String variable = "Hello Thymeleaf!";
model.addAttribute("variable", variable);
return "example";
}
${variable}
表达式来引用变量。例如:
Example
确保在控制器中返回正确的视图名称。视图名称应该与Thymeleaf模板文件的名称相匹配。例如,上述控制器中返回的视图名称为"example",则对应的Thymeleaf模板文件应该为"example.html"。
确保在项目中正确配置了Thymeleaf模板解析器。在Spring Boot项目中,默认的Thymeleaf自动配置通常已经包含了必要的配置。如果是非Spring Boot项目,需要手动配置Thymeleaf模板解析器。
如果遵循上述步骤,但仍然无法正确渲染Thymeleaf模板中的变量,请检查控制器中是否正确设置了变量,以及模板文件的路径和名称是否正确。此外,还可以在控制器中打印日志,以确保变量的值被正确设置。