Models and Views
Returning the Model
A model is essentially a map that the view uses when rendering. There are a couple of ways to return a model, the first way is to explicitly return a map instance:def show = {
def b = Book.get( params['id'] )
return [ book : b ]
}If no explicit model is returned the controller's properties will be used as the model thus allowing you to write code like this:
class BookController {
List books
List authors
def list = {
books = Book.list()
authors = Author.list()
}
}In the above example the "books" and "authors" properties will be available in the view. A more advanced approach is to return an instance of the Spring ModelAndView class:
import org.springframework.web.servlet.ModelAndView...def index = { def favBooks = // get some books just for the index page, perhaps your favorites // forward to the list view to show them return new ModelAndView("/book/list", [ bookList : favBooks ]) }
Rendering a Response
Sometimes its easier (typically with Ajax applications) to render snippets of text or code to the response directly from the controller. For this the highly flexible "render" method can be used:render "Hello World!"The above code writes the text "Hello World!" to the response, other examples include:
// write some markup
render {
for(b in books) {
div(id:b.id, b.title)
}
}
// render a specific view
render(view:'show')
// render a template for each item in a collection
render(template:'book_template', collection:Book.list())
// render some text with encoding and content type
render(text:"<xml>some xml</xml>",contentType:"text/xml",encoding:"UTF-8")


