【问题标题】:if statements in a GSP in GrailsGrails 中 GSP 中的 if 语句
【发布时间】:2012-08-25 09:43:09
【问题描述】:

我在控制器中调用索引方法

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
}

【问题讨论】:

    标签: grails


    【解决方案1】:

    您可以使用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>
    

    【讨论】:

      【解决方案2】:

      &lt;g:if&gt; 更简洁的解决方案是使用安全取消引用运算符?

      ${childInstance?.firstName}
      

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

      【讨论】:

        【解决方案3】:
        <g:if test="${ childInstance }">
            ${ childInstance.firstName }
        </g:if>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-01
          • 1970-01-01
          相关资源
          最近更新 更多