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



我在模板中使用Thymelaf。

我有一个问题:我需要使用一个条件生成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>

Thymelaf了解范围。因此,要解决此问题,您需要将${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>

我鼓励您在标记之间保留一些默认文本(在这种情况下为"此处标题"(,这样UI设计器就可以查看页面,而无需运行容器。

最新更新