withFormat

Purpose

Used to execute different responses based on the incoming request Accept header, format parameter or URI extension. See content negotiation for more information.

Examples

import grails.converters.*

class BookController { def books def list = { this.books = Book.list() withFormat { html bookList:books js { render "alert('hello')" } xml { render books as XML } } } }

Description

The withFormat method takes a block within the scope of which you can execute different methods whose names match the content type you want to respond to. For example:

withFormat {
	html bookList:books
	js { render "alert('hello')" } 
	xml { render books as XML }
}

Here we invoke three methods called html, js and xml that use mime type names configured in grails-app/conf/Config.groovy (See content negotiation for more information). The call to html accepts a model (a map) which is passed on to the view. Grails will first search for a view called grails-app/views/book/list.html.gsp and if that is not found fallback to grails-app/views/book/list.gsp.

Note that the order of the types is significant if either the request format is "all" or more than one content type has the same "q" rating in the accept header. In the former case, the first type handler in the block is executed ("html" in the short example above). The latter case is more confusing because it only holds if there is more than one content type with the highest "q" rating for which you have a type handler and you have more than one type handler matching that "q" rating. For example, say the request has "text/html" and "application/xml" with a "q" rating of 1.0, then this code:

withFormat {
    xml { … }
    html { … }
}
will use the "xml" type handler for the request.

If you require the model to be lazily executed you can pass a closure or block instead of a map:

withFormat {
	html { [bookList:Book.list()] }
    …
}

The block will only get executed if the html format is matched.