Grails 2.3.3 namespaced controller render view

匆匆过客 提交于 2019-12-11 04:38:54

问题


For Grails 2.3.3, it allows same name controller in different package with namespaced controller according to http://grails.org/doc/latest/guide/theWebLayer.html#namespacedControllers

So we have package like this:

/admin/FooController
/public/FooController

To keep consistent we want the view package like this:

/views/admin/foo/...
/views/public/foo/...

However, in the FooController action, if you don't hard code the render method. It will find the view in the

/views/foo/index....

It seems it can't take advantage of namespace. We have to hard code.

Anyone has good idea for that?


回答1:


You can certainly do this. Take a look at this post by Sérgio Michels shows how to render views from different directories using afterInterceptor. The idea is to substitute the default view before its getting rendered.

So your controller will be something like this:

package test.xpublic

class FooController {
    static namespace = 'public'
    def afterInterceptor = { model, modelAndView ->         
        if (modelAndView.viewName.contains('index')) {
            modelAndView.viewName = "/public/index"
        }
    }
    def index() { }
}

You can be creative and make it smart to pick the right view, since afterInterceptor will be called for each action.

This will help you to render the view from your directory (views/admin or views/public). However, you also need to take care of the UrlMappings

class UrlMappings {
    static mappings = {
        "/foo/admin" {
            controller="foo"
             namespace = 'admin'
        }

        "/foo/public" {
            controller="foo"
            namespace = 'public'
        }
...
}

and finally on the links you need to pass the namespace.

<g:link controller='foo' namespace="admin" >Admin</g:link>
<g:link controller='foo' namespace="xpublic">Public</g:link>

A sample application is provided here




回答2:


At least with Grails 3.2.0 this is working out of the box. See http://docs.grails.org/latest/guide/theWebLayer.html#_selecting_views_for_namespaced_controllers for more details



来源:https://stackoverflow.com/questions/19943271/grails-2-3-3-namespaced-controller-render-view

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