gpt4 book ai didi

spring - Spring Boot 中何时需要 Thymeleaf 表达式分隔符?

转载 作者:行者123 更新时间:2023-12-03 21:10:18 24 4
gpt4 key购买 nike

我正在使用带有 Thymeleaf 的 Spring Boot 2.3.3.RELEASE。从 Thymeleaf 文档中,我不清楚何时必须使用 ${} Thymeleaf 表达式中的分隔符。
例如,我的模板中有这个,它正在工作:

<div th:title="${doTest() ? 'foo' : 'bar'}" />
但是后来我重新阅读了文档,我发现我可以使用它:
<div th:title="${doTest()} ? 'foo' : 'bar'" />
但是 ? … : …三元运算符是一个运算符,因此整个事情就是一个表达式。那么为什么我不需要 ${}围绕整个属性值?
我也可以这样做吗?
<div th:title="doTest() ? 'foo' : 'bar'" />
那这个呢?
<div th:title="'foo'" />
为什么是一个而不是另一个?
那这个呢?我可以只使用裸机吗 true ?
<div th:if="true">…</div>
还是我需要表达式分隔符?
<div th:if="${true}">…</div>
这是另一个示例:我在文档中看到了这一点:
<li th:text="${item.description}" …
但我可以只使用 th:text="item.description" ?牙套对我有什么作用?
我也看到这个:
th:each="item : ${items}"
我可以用 th:each="item : items"吗?反而?为什么 Thymeleaf 不知道评估 items没有 ${items} 中的大括号?
当我需要时,肯定有一些简单的规则 ${} ,但这并不是很明显。

最佳答案

使用不带 ${} 的表达式将被视为 的混合值 (strings, numbers booleans ...),操作和条件,因此 thymeleaf 将尝试按原样执行表达式。这是 Thymeleaf 标准表达式引擎
例如 :th:text="item.description" : 将显示 item.description , 如果你做同样的事情 th:text="'item.description'"因为 thymeleaf 看着item.description作为文本 docs .
正在使用 ${}带有表达式,将被视为变量表达式,这意味着每个文字标记(不带 '' 的文本)都是一个将在预定义上下文中执行的变量。这是 OGNL(对象图导航语言)
在我们的例子中:th:text="${item.description}" : 将在上下文中显示项目对象的描述。在 spring 中,您可以使用 Model 在上下文中注册您的对象。 (或 ModelAndView):model.addAttribute("item", new Item());如果没有 item,这将引发异常在上下文中找到。
所以th:text="${'item.description'}"th:text="item.description"是相同的,但它们的评估方式不同。
我认为现在很清楚,如果您想从模板中访问对象(模型、服务、存储库...),您应该使用 ${} .

关于spring - Spring Boot 中何时需要 Thymeleaf 表达式分隔符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64321457/

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