DEV Community

Joe McCall
Joe McCall

Posted on • Originally published at joemccall86.gitlab.com on

Grails Views - Rendering Empty Lists

Do you have a controller action that looks like this?

def index() {
  respond myService.listItems()
}

Enter fullscreen mode Exit fullscreen mode

Does that controller show a view like this?

model {
  List<Item> itemList
}

json g.render(itemList)

Enter fullscreen mode Exit fullscreen mode

This may appear to work fine when itemList is populated, but you may notice that the API is broken when the index method is run when there are no items in the list:

$ curl http://localhost:8080/api/items
[
   null
]

Enter fullscreen mode Exit fullscreen mode

What? This is supposed to render [] because we’re responding with an empty list. What happened?

Let’s look at this from the documentation found here: http://views.grails.org/latest/

If the collection is empty, emptyCollection will be used as the default model name. This is due to not being able to inspect the first object’s type.

So the itemList field on our model is null because the auto model-binding computes to emptyCollection. There are technical reasons for this. The fastest way to fix this is to change how we call respond:

def index() {
  respond([itemList: myService.listItems()])
}

Enter fullscreen mode Exit fullscreen mode

This forces the itemList in the model to be bound manually, whether it is empty or not.

Top comments (0)