2012-08-30 69 views
12

我在GSP页面调用一个控制器if语句在GSP中的Grails

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

中的索引方法我有

${childInstance.firstname} 

哪个,如果我传递一个childInstance,这是好的,但如果我我没有得到一个500,因为空指针是否有办法,我可以做一个gsp的if语句,所以我可以做到这一点

if(childInstance){ 
    ${childInstance.firstname} 
} else { 
    All 
} 

回答

35

您可以使用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> 
3
<g:if test="${ childInstance }"> 
    ${ childInstance.firstName } 
</g:if> 
4

一个更简洁的解决方案比<g:if>是使用安全,引用操作?

${childInstance?.firstName} 

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