Grails 2.3.3 命名空间 Controller 渲染 View

标签 grails grails-2.0 grails-controller

对于 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/

相关文章:

sql - Grails过滤器统计信息插入效果

grails - 无法在Grails/Groovy Tool Suite 3.6中运行Grails应用程序

authentication - 登录后Grails 3重定向

grails - spring-security-core:2.0-RC5给出错误

grails - 从1.3.x升级到2.0.4后,出现错误 “unable to resolve class org.jfree.util.Log grails”

grails - 如何将值从 Controller 传递到gsp页面

mysql - 使用多个 JOINS 将 MYSQL 查询转换为 HQL

gwt - 如何使GWT插件与Grails一起运行?

json - 使用Groovy JSON构建器

ajax - 如何从 Controller 调用身份验证-Spring Security Core插件