Grails Layouts: Better know a framework


A colleague of mine stated this quote the other day, with a sense of frustration:

Why is there a layout being applied to this view? I’m not assigning a layout to it!

He had recently upgraded a Grails application from 1.0.4 to 1.1, and was now getting a mystery style attached to his template.

So we scratched our heads for a couple minutes and saw that the layout that was being applied had the same name as the controller that was rendering the template.

So we dug through the Grails Docs and saw that Grails 1.1 has applied the convention over configuration paradigm to lay out assignment. Kind of cool if you know about, temporarily frustrating if you don’t.

So here is an example of how it works.

If you have a the following controller in the grails controller directory (grails-app/controllers/)

class BookController {
    def list = {...}
}

You can then have a layout called grails-app/views/layout/book.gsp

This layout will dynamically be associated to all views the the BookController delegates to.

You can take this a step further and also dynamically assign a layout to a specific action in a view. For this example if we wanted to assign a layout to the list action in the book controller we would just create a template in the following folder:

/grails-app/views/layout/book/list.gsp

And the list.gsp layout will be applied to the BookControlelr list action.

My initial reaction to this was one of skepticism:

This is taking convention over configuation a little too far? You are only saving one line of code in your view and it seems to > defiy the principle of least supprise.

If there is one thing I’ve learned it’s that if I have a knee-jerk reaction to something then I usually need to think about it some more.

What I realized is that this now allows us to create more generic and modular views and templates. We can create them with reuse in mind and then skin them for the context that they are being used.

This is cool stuff, you just have to know about it.

  1. No comments yet.
(will not be published)
  1. No trackbacks yet.