对于 Grails 2.3.3,它允许不同包中的同名 Controller 与命名空间 Controller 根据 http://grails.org/doc/latest/guide/theWebLayer.html#namespacedControllers
所以我们有这样的包:
/admin/FooController
/public/FooController
为了保持一致,我们希望 View 包像这样:
/views/admin/foo/...
/views/public/foo/...
但是,在 FooController 操作中,如果您不对渲染方法进行硬编码。它将在
中找到 View/views/foo/index....
它似乎无法利用命名空间。我们必须进行硬编码。
有人对此有什么好主意吗?
最佳答案
你当然可以做到这一点。看看 Sérgio Michels 的这篇文章展示了如何使用 afterInterceptor 渲染来自不同目录的 View 。这个想法是在渲染之前替换默认 View 。
所以你的 Controller 将是这样的:
package test.xpublic
class FooController {
static namespace = 'public'
def afterInterceptor = { model, modelAndView ->
if (modelAndView.viewName.contains('index')) {
modelAndView.viewName = "/public/index"
}
}
def index() { }
}
您可以发挥创意并明智地选择正确的 View ,因为每个操作都会调用 afterInterceptor
。
这将帮助您从目录(views/admin 或views/public)渲染 View 。但是,您还需要注意 UrlMappings
class UrlMappings {
static mappings = {
"/foo/admin" {
controller="foo"
namespace = 'admin'
}
"/foo/public" {
controller="foo"
namespace = 'public'
}
...
}
最后在需要传递 namespace 的链接上。
<g:link controller='foo' namespace="admin" >Admin</g:link>
<g:link controller='foo' namespace="xpublic">Public</g:link>
提供了示例应用程序 here
关于Grails 2.3.3 命名空间 Controller 渲染 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19943271/