在Grails中的GSP中的if语句

18

我在控制器中调用了一个索引方法。

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")
    }
}

在GSP页面中,我有以下内容:

${childInstance.firstname}

如果我传递一个childInstance,那么一切都好,但是如果我不这样做,由于空指针我会得到500错误,有没有办法在gsp中做一个if语句来解决这个问题?

if(childInstance){
   ${childInstance.firstname}
} else {
   All
}
3个回答

50
你可以使用 g:ifg:elseifg: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>

6
<g:if>更简洁的解决方案是使用安全调用运算符?
${childInstance?.firstName}

如果childInstance不为空,将显示第一个名字,如果为空,则不显示任何内容。

3
<g:if test="${ childInstance }">
    ${ childInstance.firstName }
</g:if>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接