Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GSP if check on possible null object

Tags:

grails

gsp

I have the following code

<g:if test="${cart == null || cart.isEmpty()}"> 
    Cart is Empty   
</g:if>
<g:else>
    ${cart.size()} items
</g:else>

but the first time I access the site (when cart is null) I get a "Cannot invoke method isEmpty() on null object" exception

like image 318
Matt Westlake Avatar asked Dec 25 '22 00:12

Matt Westlake


1 Answers

This can be rewritten as

<g:if test="${cart}"> 
    ${cart.size} items    
</g:if>
<g:else>
    Cart is Empty
</g:else>

If a variable is null or a Lists size is 0, it will be False according to the Groovy truth.

like image 160
secondbreakfast Avatar answered Feb 02 '23 11:02

secondbreakfast