Grails 2.3.3 namespaced controller render view

2019-07-18 06:03发布

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?

2条回答
We Are One
2楼-- · 2019-07-18 06:33

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

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-07-18 06:34

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

查看更多
登录 后发表回答