Search code examples
grailsgrails-controller

Grails render v respond - conventions for passing to data to the controller


Some of the Grails conventions for passing data from the controller to the view I find a bit opaque notwithstanding reading the documentation. A few basic questions:

Here are some questions:

1) in the scaffolding created for a 'Person' controller, the index action ends with

respond Person.list(params) model:[personCount: Person.count()]

In in index.gsp, the list is rendered to the browser using:

<f:table collection="${personList}" />

My question is, where did this personList variable come from? Or put another way, how did the output of Person.list(...) in the controller show up in the view with the name personList? Is there a generalizable rule about if you call

respond foo

and foo is a list, then it will show up in the controller under the name "fooList"?

2) If you can provide a object to the controller just by saying "render foo", what is the purpose of the model parameter? i.e. is there some difference between

respond foo

and

respond model:[foo: foo]

It seems like both would be accessible in the view using "${foo}"

3) Finally, what is a concise description of the difference between "respond" and "render"? They both seem to deliver data from the controller to the view.


Solution

  • So, the documentation does a very good job of explaining both respond and render and points out the differences between the two. Specifically the questions you asked.

    However, I'll answer them here anyway:

    1. When using respond it will attempt to determine the appropriate model variable name based on the type. So for your example, since Person.list() returns a List the model variable becomes personList and in your other example if foo is a List it does become fooList. This is explained in the documentation about respond (with specific examples).
    2. respond and render are diffrent in that respond attempts to reply with the most appropriate model based on the accept header (or file extension). Where as render allows you more specific control to render the response regardless of the accept header (or file extension). This also is made clear in the description of both in the documentation.
    3. The concise description of the differences are found in the description of both respond and render (from the documentation):

    Respond: Attempts to return the most appropriate type for the requested content type (specified by either the Accept header or file extension)

    and

    Render: To render different forms of responses from simple text responses, to view and templates.

    To put this simply: "Use respond when you want to support many types of response types and follow the Grails convention, and use render when you want more specific control of the response type.