Search code examples
grailsgrails-3.0

Grails View thinks model is null


I have a Grails 3 app and I'm trying to use a view to marshall the output of my controller into a specific format. I add two views: 1. a model tied to the controller action under views/order/getOrderLines.gson and 2. a template for individual orderLines views/order/_orderLines.gson

However my output comes back as an empty object. It is really difficult to figure out. Here are my views: views/order/getOrderLines.gson

model {
  List<OrderLine> orderLinesList
}
json tmpl.orderLines(orderLinesList)

views/order/_orderLine.gson

model {
  OrderLine orderLine
}
json {
  id orderLine.id
  description orderLine.description
  ...
}

But I get a NullPointerException on orderLine, as if there was not a List<OrderLine> being returned from the OrderController. When I delete these views, the output returns just as expected, although it isn't marshalled the way I'd like it to be.

The weirdest thing: this works for most of my other views. I found a lot of great documentation at Grails Views' documentation but nothing seems to be covering this strange error.


Solution

  • Proper way of working with templates should be like this:

    File _orderLine.gson

    import com.example.OrderLine
    
    model{
        OrderLine orderLine
    }
    
    json{
        id orderLine.id
        description orderLine.description
        ...
    }
    

    File getOrderLines.gson

    import com.example.OrderLine
    
    model{
        Iterable<OrderLine> orderLineList
    }
    
    json tmpl.orderLine(orderLineList ?: [])
    

    Notice singular orderLineList not orderLinesList, same with variable name orderLine not orderLines

    As sct999 said, name of model variable is same as used template name. But that is just by default. You can even be this explicit:

    g.render(template:'<path to template>', collection: <your collection>, var: '<target variable>')