Wednesday, October 27, 2010

Grails - custom view engine

Hi there!

Following the last post I was wondering how hard it is to actually create your own artificial view engine for your custom file format. The reason for that might be for example that you want to create Excel files from data returned by an action (like a list of people for example).

I'll assume that the view engine will be completely artificial which means it will not use any resources other than the model being passed on from controller.

Here are the steps one needs to do to make it happen:

1. Register your format so that it is recognized by the system.
2. Implement the ViewResolver and register it as a bean in beans.groovy
3. Implement the actual View and it's "render" method.

Not going into the details here's an example that works. After you run it navigate to http://localhost:8080/example/home/index to see the HTML representation and then to http://localhost:8080/example/home/index.example to see the custom format being rendered instead of the GSP page.

Hope it helps someone :)

No comments: