【发布时间】:2017-01-06 16:25:49
【问题描述】:
好吧,由于 Spring Boot 框架推荐 Thymeleaf 模板引擎,所以我创建了一个简单的项目,其中使用 http://start.spring.io 选择了 Web 和 Thymeleaf 依赖项。
因为下面的HomeController 和home/about.html 模板工作正常。
这是HomeController的java源码:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
@RequestMapping("/home/about")
public String about(Model model) {
model.addAttribute("title", "About");
return "home/about";
}
}
这是home/about.html的html源代码:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Test for dot!</title>
</head>
<body>
<h1 th:text="${title}">H1Title</h1>
</body>
</html>
当我更改模型属性名称时,带有一些点,例如home.about.title,完整代码如下:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
@RequestMapping("/home/about")
public String about(Model model) {
model.addAttribute("home.about.title", "About");
return "home/about";
}
}
而html代码变成这样:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>Test for dot!</title>
</head>
<body>
<h1 th:text="${home.about.title}">H1Title</h1>
</body>
</html>
嗯,发生了一些错误,这令人困惑!
那么,模型属性名称中的 dot 是怎么回事?它是保留使用的特殊字符吗?以及如何让它发挥作用?
我在 StackOverflow 中搜索并找到了一个类似的问题 How to access a Spring MVC model attribute name that contain a dot in Freemarker?,但该问题的答案不适用于 Thymeleaf。
【问题讨论】:
-
不是这方面的专家,但我认为 thymeleaf 正在寻找带有“about”字段的属性“home”,它本身带有一个子字段“title”。好像你已经完成了
model.addAttribute("home", new Home(new About("title"))); -
@alexbt 好吧,我也有同样的想法,但我找不到任何官方文档指定该限制或模糊用法。实际上,我什至不知道
home.about.title是否是文本区分的最佳实践。 -
当你在属性名称中使用点时,你使用的是一个关键字符,那么在你看来,thymeleaf 认为对象“home”有一个名为“about”的属性,这也有一个 final 属性称为“标题”,这是不正确的,这就是失败的原因。有同事说,用i18国际化
标签: spring spring-mvc spring-boot thymeleaf