Grails: use controller from index.gsp

梦想与她 提交于 2019-12-05 21:38:21

问题


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


回答1:


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>


来源:https://stackoverflow.com/questions/4279134/grails-use-controller-from-index-gsp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!