Hary
Hary

Reputation: 1218

What is the Difference between render and return render in Grails

What is the difference between the following in grails:

render xyz

return render xyz

i have return render xyz in a controller action and that controller action gets called multiple times in IE. I am wondering if return render is the culprit. This works fine in local intellij tomcat app server but fails in production weblogic server.

Upvotes: 2

Views: 3585

Answers (2)

Burt Beckwith
Burt Beckwith

Reputation: 75681

render is a void method, so it has no return value, and returning its return value is equivalent to returning null. Groovy treats returning nothing (e.g. just a simple return statement) and returning null as equivalent, and the return value of controller actions is ignored unless the value is a Map since the "result" of a controller action isn't necessarily something that's returned, but rather done.

Specifically this means that you can issue a redirect, a forward, or a render call, and these trigger the expected responses. If you return a Map however, it's inferred that it was the model map to be used to render the GSP with the same name as the action in the controller's views folder, e.g. the bar action in FooController renders grails-app/views/foo/bar.gsp.

If you have a logic branch, e.g. in a save action where a successful result is followed by a redirect to the show action, but a failure result results in a re-rendering of the edit page with previous values and errors to be shown, you can use a simple if/else, e.g.

if (successful) {
   redirect ...
}
else {
   render ...
}

or you can return early, e.g.

if (successful) {
   redirect ...
   return
}

render ...

So what you're seeing is combining those two lines into one:

if (successful) {
   return redirect ...
}

render ...

It's a bit of a hack since it implies that you're returning what redirect (or some other void method) returns, but you're just returning nothing. It works and it's valid, but my preference is to keep the return statement on its own line since there's no ambiguity about what's happening.

Upvotes: 9

randal4
randal4

Reputation: 590

You shouldn't need to return render. If render is the last statement in your method it should automatically return. If render is not your last statement, you can put a return line after to force the return. This question is similar (although not the same but it touches on returning after render) https://stackoverflow.com/a/8714846/1410671 . I've always seen it written as:

render xyz

Upvotes: 0

Related Questions