Best practices for grails index page

danb picture danb · Oct 13, 2008 · Viewed 23.5k times · Source

What is the right way to populate the model for the index page in a grails app? There is no IndexController by default, is there some other mechanism for getting lists of this and that into the model?

Answer

Ed.T picture Ed.T · Oct 15, 2008

I won't claim that this is the right way, but it is one way to start things off. It doesn't take much to have a controller be the default. Add a mapping to UrlMappings.groovy:

class UrlMappings {
    static mappings = {
      "/$controller/$action?/$id?"{
            constraints {
                // apply constraints here
            }
        }
      "500"(view:'/error')
     "/"
        {
            controller = "quote"
        }
    }
}

Then add an index action to the now default controller:

class QuoteController {

    def index = {
        ...
    }
}

If what you want to load is already part of another action simply redirect:

def index = {
    redirect(action: random)
}

Or to really get some reuse going, put the logic in a service:

class QuoteController {

    def quoteService

    def index = {
        redirect(action: random)
    }

    def random = {
        def randomQuote = quoteService.getRandomQuote()
        [ quote : randomQuote ]
    }
}