首页 > 解决方案 > Thymeleaf th:带有条件的局部变量赋值

问题描述

我在我的模板中使用 Thymeleaf。

我有这个问题:我需要title使用条件生成局部变量。

<title th:with="title=(${firstName} == null and ${lastName} == null) ? 'TITLE A' : 'TITLE B'" th:remove="tag"></title>
<title th:text="${title}"></title>

使用此代码,进入结果模板,我得到<title></title>

标签: javahtmlspring-bootthymeleaf

解决方案


Thymeleaf 了解范围。因此,要解决此问题,您可能希望将${title}变量嵌套在<title>标签之间或同一标签内:

<title th:with="title=(${firstName} == null and ${lastName} == null) ? 'TITLE A' : 'TITLE B'" th:text="${title}">[Title Here]</title>

或者

<title th:with="title=(${firstName} == null and ${lastName} == null) ? 'TITLE A' : 'TITLE B'">
       <span th:text="${title}" th:remove="tag">[Title Here]</span>
</title>

但是,您的情况可以简化为:

<title th:text="${firstName} == null and ${lastName} == null ? 'TITLE A' : 'TITLE B'">[Title Here]</title>

我鼓励您在标签之间保留一些默认文本(在本例中为“Title Here”),以便 UI 设计人员无需运行容器即可查看页面。


推荐阅读