GTemp
GTemp

Reputation: 209

Thymeleaf Template not rendering param value inside th if condition

I am using thymeleaf template for my spring boot application. Here below the main page,

<div th:replace="content :: content"></div>

and inside content fragment,

<div th:fragment="content">
   <h4 th:if="${param.val== 'abc'}">SOME-TEXT</h4> // not working
   <h4 th:if="${param.val== 'abc'}" th:text="${param.val}"></h4> // not working
   <h4 th:text="${param.val}"></h4> // working and value is abc
   <h4 th:unless="${param.val== 'abc'}" th:text="${param.val}"></h4> // working - value in html text is abc
<h4 th:unless="${param.val== 'abc'}">SOME-TEXT</h4> // Working, value is SOME-TEXT
</div>

URL: domain/?val=abc

I want to display: SOME-TEXT in html if param.val == 'abc'. Value 'abc' is coming inside th:text. But inside th:if failing.

Seems some hidden extra strings added to param.val? Any suggestion?

Upvotes: 2

Views: 2612

Answers (1)

andrewJames
andrewJames

Reputation: 21910

The Thymeleaf function ${param.val} will return a request parameter called val. But this could be a multivalued object (e.g. an array) - for example consider this (which is a valid construction):

?val=abc&val=def

So to work with a single-valued string, you can do this:

<h4 th:if="${#strings.toString(param.val)} == 'abc'" th:text="'SOME-TEXT-2'">SOME-TEXT-1</h4>

This prints SOME-TEXT-2 in the web page.

Or you can use this:

<h4 th:if="${#strings.toString(param.val)} == 'abc'">SOME-TEXT-1</h4>

Which prints SOME-TEXT-1.

Just out of interest, if you used that first example val=abc&val=def, then you can see what happens with this:

<h4 th:text="${param.val}"></h4> 

It prints an array:

[abc, def]

You may see something like this when processing a series of related checkboxes (just as one example).

Update:

For a null-check, using Thymeleaf, you can do this:

<h4 th:if="${param.val} != null and 
           ${#strings.toString(param.val)} == 'abc'">SOME-TEXT-2</h4>

In this specific case, it isn't really needed, as you are not doing anything with the null value which might cause a problem.

It's more relevant if you are chaining values in objects foo.bar.baz - and you need to check if foo or bar are null to avoid a null pointer exception.

Bear in mind that Spring's expression language has the safe navigation operator, which can be very helpful in such cases: foo.?bar.?baz, allowing you to write more concise null handling than with Thymeleaf alone. But again, not relevant to your specific example from the question.

Upvotes: 2

Related Questions