Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statements in a GSP in Grails

Tags:

grails

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
}
like image 543
Sagarmichael Avatar asked Aug 30 '12 15:08

Sagarmichael


3 Answers

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>
like image 200
Roberto Perez Alcolea Avatar answered Nov 16 '22 18:11

Roberto Perez Alcolea


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.

like image 35
Dónal Avatar answered Nov 16 '22 18:11

Dónal


<g:if test="${ childInstance }">
    ${ childInstance.firstName }
</g:if>
like image 3
Tom Metz Avatar answered Nov 16 '22 18:11

Tom Metz