Grails: use controller from index.gsp

elCapitano picture elCapitano · Nov 25, 2010 · Viewed 13.3k times · Source

i am new to grails and i want to use a method from a specific controller in my index.gsp

In Index.gsp i tried

<g:each in="${MyController.myList}" var="c">
     <p>${c.name}</p>
</g:each>

but it says that the property is not available.

MyController contains a property like:

   def myList = {
       return [My.findAll()  ]
   }

What am i doing wrong? Is there a good tutorial about the communication between the grails-parts?

Or is there a better way to get information printed via gsp?

Thanks

Answer

ataylor picture ataylor · Nov 25, 2010

Generally, when using the Model-View-Controller pattern, you don't want your view to know anything about controllers. It's the controller's job is to give the model to the view. So instead of having index.gsp respond to the request directly, you should have a controller handle it. The controller can then get all the domain objects necessary (the model), and pass them on to the view. Example:

// UrlMappings.groovy
class UrlMappings {
    static mappings = {
        "/$controller/$action?/$id?"{
            constraints {
                // apply constraints here
            }
        }

        "/"(controller:"index") // instead of linking the root to (view:"/index")
        "500"(view:'/error')
    }
}

// IndexController.groovy
class IndexController {
    def index() {  // index is the default action for any controller
        [myDomainObjList: My.findAll()] // the model available to the view
    }
}

// index.gsp
<g:each in="${myDomainObjList}" var="c">
    <p>${c.name}</p>
</g:each>