Thursday, February 3rd, 2011

Grails: Controller and Action Names in GSP

Grails is a powerful framework for building web applications in Groovy. This post is about a tiny little corner of Grails development.

The presentation layer in Grails, also known as views, is built from Groovy Server Pages (GSP). The names of the controller and action that spawned a view are not automatically available in the view. This post shows you a very simple way to provide those names to views.

Controller and action names are available to filters. The idea is to create a filter that copies data to a context available to the view. In this example we have chosen to store them in flash scope. Here is the source code, to be stored in grails-app/conf.

GROOVY:

  1. class MyFilters {
  2.     def filters = {
  3.         controllerDetails(controller:'*', action:'*') {
  4.             before = {
  5.                 flash.controllerName = controllerName
  6.                 flash.actionName = actionName
  7.             }
  8.         }
  9.     }
  10. }

You may change most of the names, except that the class name must end in Filters, and the name of the outermost closure must be filters.

Comments are closed.