Safari
Safari

Reputation: 11965

Thymeleaf th:with assignment of a local variable with a condition

I'm using Thymeleaf into my templates.

I have this problem: I need to generate the title local variable using a condition.

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

using this code, into the resulted template, I obtain <title></title>

Upvotes: 0

Views: 2201

Answers (1)

riddle_me_this
riddle_me_this

Reputation: 9155

Thymeleaf understands scope. So to fix this, you would want either have the ${title} variable nested between the <title> tags or within the same tag:

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

Or

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

But, your case can be simplified to:

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

I would encourage you to keep some default text between the tags ("Title Here" in this case), so that a UI designer can view the page without having to run a container.

Upvotes: 2

Related Questions