Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect which view file has been rendered in grails

Tags:

filter

grails

I have to know the view file when it is rendered by grails. One way is grails afterView action in filter. Here, I couldn't find a way to know which view file has been rendered. So, Is there any method through which I know which view file has been rendered by render method in action?

like image 788
Sumit Shrestha Avatar asked Feb 15 '23 21:02

Sumit Shrestha


1 Answers

This isn't pretty, but it should work in most cases. Use this in either after or afterView:

String viewName
def webRequest = RequestContextHolder.currentRequestAttributes()
if (webRequest.renderView) {
   def controller = request.getAttribute(GrailsApplicationAttributes.CONTROLLER)
   def modelAndView = getModelAndView()
   if (!modelAndView && controller) {
      modelAndView = controller.modelAndView
   }
   if (modelAndView) {
      viewName = modelAndView.viewName
   }
   else if (controller) {
      // no ModelAndView, so infer from controller and action
      viewName = '/' + controllerName + '/' + actionName
   }
   else {
      // no controller, direct GSP
      String uri = webRequest.attributes.urlHelper.getPathWithinApplication(request)
      for (info in WebUtils.lookupUrlMappings(servletContext).matchAll(uri)) {
         if (info?.viewName) {
            viewName = info.viewName
            break
         }
      }
   }
}

You'll need these imports:

import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes
import org.codehaus.groovy.grails.web.util.WebUtils
import org.springframework.web.context.request.RequestContextHolder
like image 135
Burt Beckwith Avatar answered Mar 05 '23 16:03

Burt Beckwith