I call an index method within a controller
def index() {
childInstance = Child.get(params.id)
if(childInstance){
System.out.println("CHILD" + childInstance.firstname)
def messages = currentUserTimeline()
[profileMessages: messages,childInstance:childInstance]
} else {
def messages = currentUserTimeline()
[profileMessages: messages]
System.out.println("ALL")
}
}
in the gsp page I have
${childInstance.firstname}
Which if i pass a childInstance this is fine but if I don't i get a 500 because of a null pointer is there a way I can do an if statement in a gsp so i can do this
if(childInstance){
${childInstance.firstname}
} else {
All
}
You can use g:if
, g:elseif
and g:else
:
<g:if test="${name == 'roberto'}">
Hello Roberto!
</g:if>
<g:elseif test="${name == 'olga'}">
Hello Olga!
</g:elseif>
<g:else>
Hello unknown person!
</g:else>
A more concise solution than <g:if>
is to use the safe-dereference operator ?
${childInstance?.firstName}
will display the first name if childInstance
is not null and display nothing if it is null.
<g:if test="${ childInstance }">
${ childInstance.firstName }
</g:if>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With