Grails: How can I change default view location?

自闭症网瘾萝莉.ら 提交于 2019-12-06 02:19:35

It's possible to change it with the afterInterceptor of your controller. Check the example:

def afterInterceptor = { model, modelAndView ->
    println "Current view is ${modelAndView.viewName}"
    if (model.someVar) {
        modelAndView.viewName = "/mycontroller/someotherview"
    }
    println "View is now ${modelAndView.viewName}"
}

This is applied to all actions of your controller.

In your case, I would do the heavy work in the controller, as only one class is impacted.

However, here is another way, using a custom GroovyPageResourceLoader.

That approach is typically used when your views are in a folder structure that doesn't follow Grails conventions. In your case, that would be overkill in my opinion.

However, here's the general idea:

1. Create a class that extends the default groovyPageResourceLoader.

Below is a very raw example.

class AdminGroovyPageResourceLoader extends GroovyPageResourceLoader {

 @Override Resource getResource(java.lang.String location) {
        if (location.contains ("/admin")) {
            return new FileSystemResource("PATH_TO_GSP_LOCATION_WITHOUT_FILE_EXTENSION")
        }

        return super.getResource(location)
 }
}

2. Override the default groovyPageResourceLoader bean

In resources.groovy or your plugin descriptor, override the groovyPageResourceLoader bean with your custom class.

A shorter path, might be some metaclass kung fu, if you don't want to override the default Spring Bean.

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