Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails controller rendering method render vs respond

I just realised that for a Grails controller there is another rendering method 'respond'.

What's the difference between respond and render method if we want to render a view in the controller.

like image 800
ttt Avatar asked Mar 24 '14 04:03

ttt


People also ask

What is render in Grails?

Description. A multi-purpose method for rendering responses to the client which is best illustrated with a few examples! Warning - this method does not always support multiple parameters. For example, if you specify both collection and model, the model parameter will be ignored.

What is respond in groovy?

Using the respond method to output JSON The respond method provides content negotiation strategies to intelligently produce an appropriate response for the given client. For example given the following controller and action: grails-app/controllers/example/BookController.groovy.


1 Answers

The respond method uses content negotiation to respond with the most appropriate content type based on the requests 'ACCEPT' header.

Accept: text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8, application/json 

This way the consumer of your site can choose how they wish to be returned data. This may not be the best option if you want to force a specific return type. For example: You are building a REST api and only want to return json or xml, if the user asks for test.html then they may be returned your data in a format that you do not wish to support. Otherwise respond can be an easy way to support multiple return formats without programming them each separately.

Render explicitly defines the format you wish to return your data in :

(Examples from documentation)

render Book.list(params) as JSON render Book.get(params.id) as XML  // render with status code render(status: 503, text: 'Failed to update book ${b.id}') 

More information:

Respond: http://grails.org/doc/latest/ref/Controllers/respond.html Render:http://grails.org/doc/latest/ref/Controllers/render.html

like image 189
vesuvious Avatar answered Sep 19 '22 15:09

vesuvious