Artifact and Scaffolding Templates (since 0.4)
When creating artifacts or using scaffolding, Grails uses templates to create the domain classes, controllers, views etc. The default templates are part of the Grails distribution for out of the box behaviour, but can be customized for project specific needs.
Scenario
Imagine you are using Action Interceptors for checking if an user is authenticated. In this case, (almost) all controllers in your application need a before interceptor to do the authentication check. Easiest way to do this is to create a SecuredBaseController containing the authentication interceptor
class SecuredBaseController {
def beforeInterceptor = [action:this.&auth]
def auth() {
if(!session.user) {
redirect(controller:'authentication',action:'login')
return false
}
}
}
You then can extend this SecuredBaseController in the controllers which need to be secured. Nothing new so far. However, if almost 100% of your controllers need to be secured you will be extending this SecuredBaseController over and over again. This does not only cost you time, but it also violates DRY.
Solution
As mentioned earlier, Grails uses templates for creating artifacts and scaffolding. The default template for creating new controllers looks something like:
class @artifact.name@Controller {
def index = { }
}
When creating a new controller the @artifact.name@ will be replaced by the name you specified for the new controller.
To secure all newly created controllers by default, we need to extend the SecuredBaseController in the template:
class @artifact.name@Controller extends SecuredBaseController {
def index = { }
}
Customizing templates
To customize the templates for you project you need to the install the templates:
grails install-templates
This will create the src/templates folder in your project which will contain various artifact and scaffolding templates. These application specific templates can be customized and Grails will use them the next time you create artificats or generate scaffolding. Grails will first check if the needed template exists within the project, if it exists it will be used, otherwise the default template from the Grails distribution will be used. This also means that templates which are not used can be removed from the project.
Note that both the artifact and scaffolding template folder contain a Controller template. So in the example above both templates need to be changed to extend the SecuredBaseController.
Taking it further
Most projects will use the scaffolding generation only for prototyping or as a starting point, as the generated views need to be changed to the layout requirements of the project. This can be a really time consuming as it is not just extending some base class like the SecuredBaseController example above. You can give your development time a huge boost by changing the list, show, create and edit scaffolding templates before generating the views.