Dark theme | Light theme

July 28, 2009

Grails Goodness: Change Scaffolding Templates in Grails

The scaffolding feature in Grails is impressive, especially when we want to show off Grails to other developers. Seems like magic is happening with only a minimal of code. But what if we don't like the default pages Grails generates for us. Of course there is a way to have another layout for the dynamically generated pages.

First we start with a simple, one domain object application:

$ grails create-app scaffold-sample
$ cd scaffold-sample
$ grails create-domain-class message
$ grails create-controller message

We open grails-app/domain/Message.groovy and add the following simple attribute with a small constraint:

class Message {
    String text

    static constraints = {
        text maxLength:140

Next we add the magic code to the grails-app/controllers/MessageController.groovy:

class MessageController {
    def scaffold = true

We are ready to run the application and we are able to view, add, update or delete messages:

$ grails run-app

We see the default layout we get from Grails. To see which GSP files Grails uses to generate these pages we only have to invoke one command:

$ grails install-templates

After the script is finished we have a new directory src/templates. In this directory we find the scaffolding directory with a couple of GSP files. To change the layout of the pages we only have to make our changes here. Every controller which uses scaffolding will get these changes. Let's create a new CSS file and use it in the create.gsp, edit.gsp, list.gsp and show.gsp files.

We create a new file scaffold.css in the web-app/css directory:

body {
    background-color: #EFE14E;
.logo {
    font: 28px bold Georgia;
    color: #006DBA;
    padding: 0.3em;
table {
    background-color: #F3EFC9;

We open the files create.gsp, edit.gsp, list.gsp and show.gsp and add the following line in the HTML head section:

<link rel="stylesheet" href="\${resource(dir: 'css', file: 'scaffold.css')}"/>

Now when we run the application again we see that the dynamically generated pages are using the new CSS file:

Besides a simple change like this, we can of course do anything we want with the GSP files that are used for scaffolding. In the above screenshot we can see for example we have removed the default Grails logo and replaced it with our own text.