[英]if statements in a GSP in 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 在gsp页面中我有
${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 如果我传递一个childInstance这很好,但是如果我没有因为空指针而得到500,那么有一种方法我可以在gsp中做一个if语句所以我可以这样做
if(childInstance){
${childInstance.firstname}
} else {
All
}
You can use g:if
, g:elseif
and g:else
: 你可以使用
g:if
, g:elseif
和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>
A more concise solution than <g:if>
is to use the safe-dereference operator ?
比
<g:if>
更简洁的解决方案是使用安全解除引用运算符?
${childInstance?.firstName}
will display the first name if childInstance
is not null and display nothing if it is null. 如果
childInstance
不为null,则显示第一个名称;如果为null,则显示任何内容。
<g:if test="${ childInstance }">
${ childInstance.firstName }
</g:if>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.