2012-08-30 26 views
12

tôi gọi một phương pháp chỉ số trong một bộ điều khiểnnếu phát biểu trong một GSP trong 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") 
    } 
} 

trong trang GSP Tôi có

${childInstance.firstname} 

nào nếu tôi vượt qua một childInstance này là tốt nhưng nếu tôi tôi không nhận được một 500 vì một con trỏ null là có một cách tôi có thể làm một tuyên bố nếu trong một gsp vì vậy tôi có thể làm điều này

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

Trả lời

35

Bạn có thể sử dụng g:if, g: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

Một giải pháp ngắn gọn hơn <g:if> là sử dụng các nhà điều hành an toàn-dereference ?

${childInstance?.firstName} 

sẽ hiển thị tên đầu tiên nếu childInstance không phải là null và hiển thị không có gì nếu nó là null.

Các vấn đề liên quan