Search code examples
htmlthymeleaf

How can I hide <span> when it is empty


I am working on a user login form. It is on my "home.html" ,

I want to show the username after login(when I get session datas form

"login.html" by "Httpsession")

Otherwise just hide when it is empty.

<span th:text="${user.name}" id="uname"></span>

When it is empty, I have an error message like this:

EL1007E: Property or field 'name' cannot be found on null.

Thanks.


Solution

  • Use th:if to conditionally include the <span>:

    <span th:if="${user?.name}" th:text="${user.name}" id="uname"></span>
    

    To avoid the NullPointerException, use the Safe Navigation Operator: ?..