Java Thymeleaf th:带有条件的局部变量赋值

Java Thymeleaf th:带有条件的局部变量赋值,java,html,spring-boot,thymeleaf,Java,Html,Spring Boot,Thymeleaf,我在模板中使用了Thymeleaf 我有这个问题:我需要使用一个条件生成title局部变量 <title th:with="title=(${firstName} == null and ${lastName} == null) ? 'TITLE A' : 'TITLE B'" th:remove="tag"></title> <title th:text="${title}"></title&

我在模板中使用了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 th:with="title=(${firstName} == null and ${lastName} == null) ? 'TITLE A' : 'TITLE B'" th:text="${title}">[Title Here]</title>
[此处标题]


[此处标题]
但是,您的案例可以简化为:

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

我建议您在标记之间保留一些默认文本(“本例中为Title Here”),以便UI设计师可以在不运行容器的情况下查看页面。

Thymeleaf了解范围。因此,要解决此问题,您需要将
${title}
变量嵌套在
标记之间或同一标记内:

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


[此处标题]
但是,您的案例可以简化为:

<title th:text="${firstName} == null and ${lastName} == null ? 'TITLE A' : 'TITLE B'">[Title Here]</title>
[此处标题]
我鼓励您在标记之间保留一些默认文本(“在本例中为Title Here”),以便UI设计师无需运行容器即可查看页面