Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails: use controller from index.gsp

Tags:

grails

gsp

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

like image 587
elCapitano Avatar asked Nov 25 '10 16:11

elCapitano


1 Answers

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>
like image 200
ataylor Avatar answered Nov 17 '22 20:11

ataylor