开发者

grails/groovy braces syntax question

I'm working with an example that I can't understand what the braces do -- the ones around the "Logout" in the second "out" statement below. I guess the string is passed as a closure but I'm not getting the syntax beyond that. Can you please clarify? Note the output of the code looks like the following:

John Doe [Logout]


class LoginTagLib {
  def loginControl = {
    if(requ开发者_如何转开发est.getSession(false) && session.user){
      out << "Hello ${session.user.login} "
      out << """[${link(action:"logout",
             controller:"user"){"Logout"}}]"""
     } else {
       out << """[${link(action:"login",
       controller:"user"){"Login"}}]"""
     }
   }
}

Thanks Much


The link tag takes attributes and a body, and as a regular GSP tag it's called like this:

<g:link action="logout" controller="user">Logout</g:link>

To invoke it as a method like you're doing, you need a way to pass the text ('Logout') to render in the link. If you look at the source of the tag (click "Show Source" at the bottom of http://grails.org/doc/latest/ref/Tags/link.html) you'll see that the 2nd argument is body, and it's a Closure (although that's not clear from the code, but that's always the case for 2-parameter tags). {"Logout"} is a Closure that returns "Logout" since it's the last expression, so it's used as the body.


Actually the output should be

Hello John Doe [Logout]

Essentially, if there is a session and a user write Hello user and create a link pointing to a logout action with the label Logout.

{ "Logout" } is a closure equivalent to { return "Logout"; } as the last statement is used for a return value if none is explicitly stated.


I am not able to get the output like below

Hello John Doe [Logout]

Here is the output I am getting

Hello jdoe [Logout

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜