DEV Community

loading...

Grails Views - Rendering Empty Lists

joemccall86 profile image Joe McCall Originally published at joemccall86.gitlab.com on ・1 min read

Do you have a controller action that looks like this?

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

Does that controller show a view like this?

model {
  List<Item> itemList
}

json g.render(itemList)

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
]

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()])
}

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

Discussion (0)

Forem Open with the Forem app